Python的rename()
方法將檔案或目錄src
重新命名為dst
。 如果dst
是檔案或目錄(已存在),則會引發OSError異常。
語法
以下是rename()
方法的語法 -
os.rename(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'
]