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 Intersect Two Dictionaries in Python
How to Concatenate Items in List Into String in Python
How to Delete All Instances of Character from String in Python
How to Raise Exception in Python
How to Setup Uwsgi with NGINX for Python
How to Test Multiple Variables against a Value in Python
Python Script to Load Data in MySQL
How to Count Occurrence of List Item in Python
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.