📜  Python| os.renames() 方法

📅  最后修改于: 2022-05-13 01:54:43.073000             🧑  作者: Mango

Python| os.renames() 方法

Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。

os.renames()方法是递归的目录或文件重命名函数。它的工作方式类似于os.rename()方法,除了创建所需的任何中间目录,然后首先尝试它。重命名完成后,与旧名称最右边的路径段对应的目录将使用os.removedirs()

示例 #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']