Python3 os.renames()方法

renames() 方法将递归的目录或文件重命名功能。它同样函数 os.rename(), 但它也将文件移动到一个目录,或目录的整个树,即不存在。

语法

以下是 rename() 方法的语法:
os.renames(old, new)

参数

  • old -- 这是要重命名的文件或目录的实际名称

  • new -- 这是在文件或目录的新名称。它甚至可以包括一个文件到一个目录,或目录的整个树,即不存在。

返回值

此方法不返回任何值。

示例

下面的示例说明 rename() 方法的使用。
# !/usr/bin/python3

import os, sys
os.chdir("d:\\tmp")
print ("Current directory is: %s" %os.getcwd())

# listing directories
print ("The dir is: %s"%os.listdir(os.getcwd()))

# renaming file "aa1.txt"
os.renames("foo.txt","newdir/foonew.txt")

print ("Successfully renamed.")

# listing directories after renaming and moving "foo.txt"
print ("The dir is: %s" %os.listdir(os.getcwd()))
os.chdir("newdir")
print ("The dir is: %s" %os.listdir(os.getcwd()))
当我们运行上面的程序,它会产生以下结果:
Current directory is: d:\tmp
The dir is: ['Applicationdocs.docx', 'book.zip', 'foo.txt', 'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files', 'java.ppt', 'python2']
Successfully renamed.
The dir is: ['Applicationdocs.docx', 'book.zip', 'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files', 'java.ppt', 'newdir', 'python2']
这里文件 foo.txt 不可见,因为它已经被移动到新的目录,并更名为 foonew.txt。目录newdir 及其内容如下:
The dir is: ['foonew.txt']

上一篇: Python3文件方法 下一篇: Python3 os文件目录的方法