Python的renames()
方法是递归目录或文件重命名功能。它与os.rename()执行相同的功能,但它也将文件或目录的整个树移动到不存在的目录。
语法
以下是renames()
方法的语法 -
os.renames(old, new)
参数
- old - 这是要重命名的文件或目录的实际名称。
- new - 这是文件或目录的新名称。甚至可以将文件包含到不存在的目录或目录的整个树中。
返回值
- 此方法不返回任何值。
示例
以下示例显示了renames()
方法的用法。
# !/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
在这里不可见,因为它被移动到newdir
并重命名为foonew.txt
。 目录newdir
及其内容如下所示:
The dir is: ['foonew.txt']
上一篇:
Python os模块方法
下一篇:
Python异常处理