Python has an OS module that helps us to interact with the Operating System. The ‘os’ module comes preinstalled with python, so we do not have to pip install it. This module also allows us to interact with the file system, where we can give some name to a file, open it, or rename it. In this article, we are going to learn how to use python to rename a file.
To use the rename(), we have to import the ‘os’ module. Using rename(), we can rename multiple files at a single time, which is very handy when we have a large number of files because manually doing so is undoubtedly going to be a pain. Let say you have 100 images, and all of their names are their time of creation the image.
But you want to rename the images like ‘image1’ ‘image2’… Here comes python to the rescue. You just applied a for loop and then renamed () function, and that’s it. Impressive isn’t it. Let’s learn how to perform these types of tasks using rename().
The syntax for Python to rename a file
It is a widespread practice to use rename(), which comes under the ‘os’ module to rename the files. The syntax is-
os.rename(src, dst)
Parameters-
Src
Here ‘src,’ refers to the source of the file which you want to rename. For example, we have a text file named ‘pythonpool.txt’ in the ‘C’ directory and the articles folder, and we want to rename it to ‘pythonpool_rename.txt.’
So, src= C:\articles\pythonpool.txt
Dst
It refers to the destination of the files, including the new name of the file. If you do not want to change the file’s location, everything will be the same except for the new name.
So, dst = C:\articles\pythonpool_rename.txt
Let’s have a look at how to rename this file
import os
src=r"C:\articles\pythonpool.txt"
dst=r"C:\articles\pythonpool_rename.txt"
os.rename(src,dst)
Here, ‘r’ is used before the path of the file because it allows python to read whatever is written after it. Otherwise, we would have got this error-
(Unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape
Why Use Python to Rename a File
To convert a .jpg file into .png file.
Suppose you have an image of a dog in the same article folder in the jpg format. Sometimes you want to convert a jpg file into a png file, and one of the easiest ways to do so is by using rename(). Let’s see how.
Before,
src=r'C:\article\dog2.jpg'
dst=r'C:\article\dog2.png'
os.rename(src,dst)
Rename a directory in Python
import os
src=r"C:\article"
dst=r"C:\articles"
os.rename(src,dst)
Renaming all the files in a directory in Python
Suppose we have a folder containing images of dogs, and the names are so random. We want to convert it in the format – dog1 dog2 dog3 … For this, we have to use some more functions of the ‘os’ module. We will learn about them while learning the code.
import os
def rename_files():
#listdir() of the os module returns all the files in the folder
for count, filename in enumerate(os.listdir(r"C:\dogs")):
# Here, we will add the count
dst =r"C:\dogs" + "\\" + "dog_" + str(count) +".jpg"
src =r"C:\dogs" + "\\" + filename
# rename() function will
# rename all the files
os.rename(src, dst)
if __name__ == '__main__':
# Calling rename() function
rename_files()
Adding timestamps to the names of the files
Sometimes we want to add the current date to the name of the file. For this we will use the datetime module which comes pre-installed with python and we just have to import it.
import datetime
TodayDate = datetime.datetime.today().strftime ('%d-%b-%Y')
src=r"C:\product\product1.txt"
dst=r"C:\product\product1" + str(TodayDate) + ".txt"
Must Read:
- How to Convert String to Lowercase in
- How to Calculate Square Root
- User Input | Input () Function | Keyboard Input
- Best Book to Learn Python
Renaming file using shutil
Using the shutil library is another option to rename a file. It does not exactly rename a file, but it moves one file into another file. It is not a good option because if we want to rename a file and it is open in your system, then it will create a new file, and you will have two different files.
import shutil shutil.move(r'C:\articles\pythonpool_rename.txt', r'C:\articles\pythonpool.txt') Output- 'C:\\articles\\pythonpool.txt'
Some Common Errors while using Python to rename a file
Sometimes the path specified by us is wrong, or the directory doesn’t exist, so the interpreter gives an error. To avoid getting an error, we can check if the file exists or not. Let us learn how to do so.
import os def main(): #check if the file exist or not if path.exists(" r'C:\articles\pythonpool_rename.txt'"): src = r'C:\articles\pythonpool_rename.txt' dst=r'C:\articles\pythonpool.txt' # rename the file os.rename( src, dst) if __name__ == "__main__": main()
Conclusion
We have learned the importance of Python rename file and some of the efficient ways to perform it. We can use python to rename files when we have lots of them and renaming them manually can be very difficult.
Try to run the programs on your side and let me know if you have any queries.
Happy Coding!