當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python 3 os.rename()用法及代碼示例


描述

方法rename()重命名文件或目錄srcdst。如果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.htm', 'Java Multiple Inheritance_files', 
   'java.ppt', 'Python3'
]

Successfully renamed.

the dir is:[
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 
   'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files',
   'java.ppt', 'python2'
]

相關用法


注:本文由純淨天空篩選整理自 Python 3 - os.rename() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。