26
loading...
This website collects cookies to deliver better user experience
rename()
method is used to rename a file or directory in Python.rename()
function can rename any file type or folder in Python. # Import os module
import os
# file name old and new. This can be even absolute path
old_file_name = "python.txt"
new_file_name = "python_renamed.txt"
# use rename function to rename the file or directory
os.rename(old_file_name, new_file_name)
print("Successfully renamed a file !")
Successfully renamed a file !
rename()
method to perform batch rename.os.listdir()
method in a loop that can get all the files, iterates each file inside the loop, and use the rename()
function to rename the file.# Import os module
import os
# Batch rename all the file in the specified directory
for file in os.listdir("C:/Projects/Tryouts"):
os.rename(file, f"C:/Projects/Tryouts/old_{file}")
old_test.txt
old_python.text
old_student.csv