Python3-os-renames
提供:Dev Guides
Python 3-os.renames()メソッド
説明
メソッド* renames()*は、再帰的なディレクトリまたはファイルの名前変更機能です。 これはlink:/python3/os_rename%20 [os.rename()]と同じ機能を果たしますが、存在しないディレクトリまたはディレクトリのツリー全体にファイルを移動します。
構文
以下は* renames()*メソッドの構文です-
os.renames(old, new)
パラメーター
- 古い-これは、名前を変更するファイルまたはディレクトリの実際の名前です。
- new -これはファイルまたはディレクトリの新しい名前です。存在しないディレクトリまたはディレクトリのツリー全体にファイルを含めることもできます。
戻り値
このメソッドは値を返しません。
例
次の例は、renames()メソッドの使用方法を示しています。
# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")
print ("Current directory is: %s" %os.getcwd())
# listing directories
print ("The dir is: %s"%os.listdir(os.getcwd()))
# renaming file "aa1.txt"
os.renames("foo.txt","newdir/foonew.txt")
print ("Successfully renamed.")
# listing directories after renaming and moving "foo.txt"
print ("The dir is: %s" %os.listdir(os.getcwd()))
os.chdir("newdir")
print ("The dir is: %s" %os.listdir(os.getcwd()))
結果
上記のプログラムを実行すると、次の結果が生成されます-
Current directory is: d:\tmp
The dir is: [
'Applicationdocs.docx', 'book.zip', 'foo.txt',
'Java Multiple Inheritance', 'Java Multiple Inheritance_files',
'java.ppt', 'python2'
]
Successfully renamed.
The dir is: [
'Applicationdocs.docx', 'book.zip',
'Java Multiple Inheritance', 'Java Multiple Inheritance_files',
'java.ppt', 'newdir', 'python2'
]
結果
ファイル foo.txt は、 newdir に移動され、 foonew.txt に名前が変更されたため、ここには表示されません。 ディレクトリ newdir とその内容を以下に示します。
The dir is: ['foonew.txt']