Python os.rename()方法

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异常处理