Python os.renames()
Python os.renames()方法是递归的目录或文件重命名函数。它的工作原理类似于os.rename()方法,但需要创建任何中间目录时,它会先尝试。重命名完成后,将使用os.removedirs()删除旧名称中最右边路径段对应的目录。
语法:os.renames(old, new)
参数:
old:这是要重命名的文件或目录的旧名称。
new:这是文件或目录的新名称。它可以包括一个文件到
目录或不存在的目录树。
注意:它还可以接受新旧路径类对象。
返回值:此方法不返回任何值。
示例1
使用os.renames()方法重命名文件
# Python program to explain os.renames() method
# importing os module
import os
# path
path = 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
# Changing directory
os.chdir(path)
# Printing current directory
print ("Current directory is: ", os.getcwd())
# List files and directories
# in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
print("Before renaming file:")
print(os.listdir(os.getcwd()))
# Rename the file
# Using os.renames() method
os.renames('testfile.txt', 'new_name.txt')
# List files and directories
# in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
print("After renaming file:")
print(os.listdir(os.getcwd()))
输出:
Current directory is: C:\Users\Rajnish\Desktop\GeeksforGeeks
Before renaming file:
['testfile.txt']
After renaming file:
['new_name.txt']
示例2
使用os.renames()方法重命名文件,并将其添加到不存在的新目录中
# Python program to explain os.renames() method
# importing os module
import os
# path
path = 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
# Changing directory
os.chdir(path)
# Printing current directory
print ("Current directory is: " os.getcwd())
# List files and directories
# in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
print("Before renaming file:")
print(os.listdir(os.getcwd()))
# Rename the file and
# adding the file in new
# directory name 'newdir'
# Using os.renames() method
os.renames('testfile.txt', 'newdir / new_name.txt')
# List files and directories
# in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
print("After renaming file:")
print(os.listdir(os.getcwd()))
输出:
Current directory is: C:\Users\Rajnish\Desktop\GeeksforGeeks
Before renaming file:
['newdir', 'testfile.txt']
After renaming file:
['newdir']