Python os.renames() Method.
os.renames() Overview
The os.renames() method is used to recursively rename a directory or file. Similar to rename().
os.renames() Syntax
The syntax format of the renames() method is as follows.
os.renames(old, new)
os.renames() Parameters
- old – the directory to rename
- new – The new name of the file or directory. It can even be a file contained in a directory, or a complete directory tree.
os.renames() Return Value
This method has no return value.
os.renames() Example#1
The following example demonstrates the use of the renames() method.
#!/usr/bin/python3
import os, sys
print ("The current directory is : %s" %os.getcwd())
# List Directory
print ("The directory is : %s"%os.listdir(os.getcwd()))
# Rename "apidemos.com.sort.txt"
os.renames("apidemos.com.sort.txt","bbb/apidemos.com.sort.txt")
print ("Rename successfully.")
# List the renamed file "apidemos.com.sort.txt"
print ("The directory is : %s" %os.listdir(os.getcwd()))
Output:
Using os.renames()
method to rename a file and adding it into a new directory that do not exist
import os
# path
path = '/root/aaa-apidemos'
# Changing directory
os.chdir(path)
print ("Current directory is: " os.getcwd())
# List files and directories in '/root/aaa-apidemos'
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('apidemos.com.txt', 'ccc/ new_name.txt')
# List files and directories in '/root/aaa-apidemos'
print("After renaming file:")
print(os.listdir(os.getcwd()))
Output: