Python的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'
]
上一篇:
Python os模組方法
下一篇:
Python異常處理