renames() 方法將遞歸的目錄或檔重命名功能。它同樣函數 os.rename(), 但它也將檔移動到一個目錄,或目錄的整個樹,即不存在。
語法
以下是 rename() 方法的語法:
os.renames(old, new)
參數
-
old -- 這是要重命名的檔或目錄的實際名稱
-
new -- 這是在檔或目錄的新名稱。它甚至可以包括一個檔到一個目錄,或目錄的整個樹,即不存在。
返回值
此方法不返回任何值。
示例
下麵的示例說明 rename() 方法的使用。
# !/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 不可見,因為它已經被移動到新的目錄,並更名為 foonew.txt。目錄newdir 及其內容如下:
The dir is: ['foonew.txt']
上一篇:
Python3檔方法
下一篇:
Python3 os檔目錄的方法