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 Stored Procedure in Python
How to Randomly Select Item from List in Python
How to Remove Line from File Using Python
How to Import from Parent Folder in Python
How to Select Multiple Columns in Pandas Dataframe
How to Create Cartesian Product of Two Lists in Python
How to Remove HTML Tags from CSV File in Python
How to Sort Text File in Python

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