Automate Renaming files using Python
To automate renaming files using python we have to import os module and then initialize the paths of the files into separate variable that will be given to the rename() function as argument and then Check whether the file with the ‘new name’ already exists with the help of path.isfile() function of the os module. If it does, print a message otherwise just rename the old file to the new file.
Syntax of os.rename()
This function belongs to the os module. It is used to rename files. The syntax is given below:
Syntax: os.rename(source, destination, *, src_dir_fd = None, dst_dir_fd = None)
Parameters:
source: A path-like object representing the file system path. This is the source file path which is to renamed.
destination: A path-like object representing the file system path.
src_dir_fd (optional): A file descriptor referring to a directory.
dst_dir_fd (optional): A file descriptor referring to a directory.Return Type: This method does not return any value.
Code:
Python3
# importing the required modules import os old = "C:\\Users\\[USERNAME]\\Desktop\\old_name.txt" new = "C:\\Users\\[USERNAME]\\Desktop\\newname.txt" # check if the file with the new name already exists if os.path.isfile(new): print ( "file already exists" ) else : # rename the file to the new name # if file doesn't exist os.rename(old, new) |
Automate Renaming and Organizing Files with Python
In this article, we are going to know how to automate renaming and organizing files with Python, hence, the article is divided into two sections: one teaches us how to organize files and the latter how to rename files.