Python is a feature-rich programming language used by many software and web developers around the world. It allows you to perform numerous operations with files. Sometimes you may need to rename file using python. Here is how to rename file using python.
How to Rename File Using Python
It is very easy to rename file in Python using os library. Here is an example to rename file /home/ubuntu/data.txt to /home/ubuntu/new-data.txt
import os os.rename('/home/ubuntu/data.txt','/home/ubuntu/new-data.txt')
In the above os.rename command, you need to use the existing filename as first argument, and the new file name as the second argument.
Please remember to use full file paths for both existing and new file names. If you don’t use full file paths, then python will look for the file in current working directory.
Also, change the file path format according to your OS. In Linux, you need to use forward slash and in Windows, you need to use backward slash. The above code is to change file name in Linux. Here is the command to change file name in Windows.
import os os.rename('c:\\home\\data.txt','c:\\home\\new-data.txt')
That’s it. In this short article, we have learnt how to rename file in Python. Generally, this code is a part of larger functions and modules. So you can customize it as per your requirement.
Also read:
How to Uninstall Java in Ubuntu
How to Format USB Drive in Linux
How to Convert Epoch to Date in Linux
How to View Linux Log Files
How to Convert Files to UTF-8 in Linux
Related posts:
How to Execute Shell Command from Python
How to Reverse/Invert Dictionary Mapping in Python
How to Import CSV in Python
How to Comment in Python
How to Select Multiple Columns in Pandas Dataframe
How to Convert PDF to Text in Python
How to Iterate Through List of Dictionaries in Python
How to Convert Columns into Rows in Pandas

Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.