rename()方法重命名檔或目錄,從 src 修改命名為 dst。如果 dst 為一個檔或目錄(已經存在)引發 OSError 異常。
語法
以下是 rename() 方法的語法:
os.rename(src, dst)
參數
-
src -- 這是在檔或目錄的實際名稱
-
dst -- 這是在檔或目錄的新名稱
返回值
此方法不返回任何值。
示例
下麵的示例說明 rename() 方法的使用。
# !/usr/bin/python3 import os, sys os.chdir("d:\\tmp") # listing directories print ("The dir is: %s"%os.listdir(os.getcwd())) # renaming directory ''tutorialsdir" os.rename("python3","python2") print ("Successfully renamed.") # listing directories after renaming "python3" print ("the dir is: %s" %os.listdir(os.getcwd()))
當我們運行上面的程式,它會產生以下結果:
The dir is: ['Applicationdocs.docx', 'book.zip', 'foo.txt', 'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files', 'java.ppt', 'Python3'] Successfully renamed. the dir is: ['Applicationdocs.docx', 'book.zip', 'foo.txt', 'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files', 'java.ppt', 'python2']
上一篇:
Python3檔方法
下一篇:
Python3 os檔目錄的方法