Python3 os.rename()方法

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文件目录的方法