Python os.renames() – Recursive Directory or File Rename

Python os.renames()

Python The os.renames() method is a recursive directory or file renaming function. It works similarly to the os.rename() method, but it attempts to create any intermediate directories first. After the rename is complete, the directory corresponding to the rightmost path segment in the old name is removed using 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. This can include a file, a directory, or a non-existent directory tree.

Note: It can also accept old and new path-like objects.

Return Value: This method does not return any value.

Example 1

Rename a file using the os.renames() method

# Python program to explain the os.renames() method
       
# importing the 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()))

Output:

Current directory is: C:UsersRajnishDesktopGeeksforGeeks
Before renaming file:
['testfile.txt']
After renaming file:
['new_name.txt']

Example 2

Use the os.renames() method to rename a file and add it to a new directory that doesn’t exist

# Python program to explain the os.renames() method
       
# Importing the 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()))

Output:

Current directory is: C:UsersRajnishDesktopGeeksforGeeks
Before renaming file:
['newdir', 'testfile.txt']
After renaming file:
['newdir']

Leave a Reply

Your email address will not be published. Required fields are marked *