Python的renames()
方法是遞回目錄或檔案重新命名功能。它與os.rename()執行相同的功能,但它也將檔案或目錄的整個樹移動到不存在的目錄。
語法
以下是renames()
方法的語法 -
os.renames(old, 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.html', 'Java Multiple Inheritance_files',
'java.ppt', 'python2'
]
Successfully renamed.
The dir is: [
'Applicationdocs.docx', 'book.zip',
'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files',
'java.ppt', 'newdir', 'python2'
]
檔案foo.txt
在這裡不可見,因為它被移動到newdir
並重新命名為foonew.txt
。 目錄newdir
及其內容如下所示:
The dir is: ['foonew.txt']