Python| os.renames() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
os.renames()
方法是递归的目录或文件重命名函数。它的工作方式类似于os.rename()
方法,除了创建所需的任何中间目录,然后首先尝试它。重命名完成后,与旧名称最右边的路径段对应的目录将使用os.removedirs()
。
Syntax: os.renames(old, new)
Parameters:
old: This is the old name of the file or directory to be renamed.
new: This is the new name of the file or directory. It can include a file to a
directory or a whole tree of directories that do not exist.
Note: It can also accept a path-like object for old and new.
Return Value: This method does not returns any value.
示例 #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']
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。