In this Python tutorial, I will explain how to rename a file in Python using different methods. we’ll also explore some scenarios to illustrate these methods in Python.
Python, as a versatile programming language, provides a variety of ways to perform common file operations, such as renaming files.
Methods to rename a file in Python
There are four different ways to rename a file in Python.
- The os.rename() method
- The os.replace() method
- The shutil.move() method
- The pathlib.rename() method
Let’s explore them one by one using some examples:
Method 1: Use os.rename() method to rename a file in Python
The os module is a part of Python’s standard library, designed to provide a portable way of using operating system-dependent functionality.
The os.rename(src, dst) function is one of its simple file operation functions. It directly maps to the system’s underlying renaming function. The primary purpose is to rename a file in Python or a directory in Python from src (source name) to dst (destination name).
Syntax:
import os
os.rename(src, dst)
Scenario: Imagine we’re a budding musician in Nashville, Tennessee, often referred to as the “Music City” of the USA. We’ve just recorded a raw track titled “Nashville_Nights_raw.mp3”. After some tweaks, we want to rename it to “Nashville_Nights_final.mp3” in Python.
import os
source_name = "Nashville_Nights_raw.mp3"
destination_name = "Nashville_Nights_final.mp3"
os.rename(source_name, destination_name)
Output: The code has successfully changed the name of the file in Python.
This way we can rename a Python file using the os.rename() method.
Method 2: How to rename a file using Python with os.replace() method
The os.replace() method in Python’s standard library is designed for renaming or moving a file or directory, possibly overwriting the destination. Unlike os.rename(), the os.replace() Python method is designed to be forceful; if the destination exists and is a file, it will be replaced without prompt. If the destination is a directory, an error will be raised.
Scenario: Imagine we’re a meteorologist in Florida, a state known for its frequent hurricanes. We use specialized software in Python that generates prediction models for upcoming storms. One day, while analyzing the weather patterns, the Python software generates a model named “Hurricane_Prediction_July_Initial_Model.dat”.
As the day progresses and we receive more satellite data, the Python software updates its model. We now want to replace the initial prediction model with the updated one, named “Hurricane_Prediction_July_Updated_Model.dat” through Python.
import os
initial_model_path = "Hurricane_Prediction_July_Initial_Model.dat"
updated_model_path = "Hurricane_Prediction_July_Updated_Model.dat"
os.replace(initial_model_path, updated_model_path)
Output: The code has successfully changed the name of the Python file.
This way we can rename the Python file using the os.repalce() method.
Method 3: Python Rename File using shutil.move() method
The shutil module in Python, also part of the standard library, provides a higher-level interface for file operations.
The shutil.move(src, dst) functioning Python is useful for moving files (or directories), and during this move, it can also rename them through Python. It can work across different filesystems and takes care of many underlying details.
If the destination is a directory in Python, the source will be moved inside with its original name.
Just like the OS Python method, it can raise exceptions due to issues like permissions or non-existent files.
Scenario: We are a book reviewer in Boston. After reading a book, we draft our review and save it as “book_review_draft.txt”. Once we’ve edited and finalized our review, we decided to move it from our “Drafts” folder to a “Final_Reviews” folder and rename it to “book_review_final.txt” through Python.
import shutil
source_path = "Drafts/book_review_draft.txt"
destination_path = "Final_Reviews/book_review_final.txt"
shutil.move(source_path, destination_path)
Output:
Method 4: How to rename a file in Python using path.rename() method
Introduced in Python 3.4, the pathlib module in Python presents a set of classes to handle filesystem paths with semantics appropriate for different operating systems. The path.rename() method, under the hood, uses the os.rename() function, but it’s presented in an object-oriented manner in Python.
The advantage of Python pathlib is its intuitive handling of paths, making it more readable and easy to understand. It abstracts the differences in path naming conventions across different OS (like slashes) in Python.
This method in Python also raises exceptions for typical issues like non-existent files or permissions.
Scenario: A novelist in New York City has been working on their latest fiction piece. They saved their work on different sections of the book as individual files in a directory in Python. Initially, they named a segment about Central Park as “chapter_unknown.txt”, but after finalizing the sequence, they decided to rename it to “chapter_5_Central_Park.txt” through Python.
from pathlib import Path
source_path = Path("chapter_5_Central_Park.txt")
destination_path = "chapter_5_Central_Park.txt"
source_path.rename(destination_path)
Output:
This way we can rename a file in Python using pathlib.rename().
Conclusion
This article explains how to rename a file in Python using four different methods such as os.rename(), os.replace(), shutil.move(), and pathlib.rename() with illustrative examples.
Each method offers its unique advantages: os for direct operations, shutil for high-level utilities, and pathlib for an object-oriented and cross-platform approach. The choice depends on the application’s specific needs and the developer’s preference.
Yoy may also like to read:
- Read the file as a string in Python [5 Methods]
- How to get all files in a directory in Python?
- 6 Ways to Save image to file in Python
- How to Install Python on Windows 10
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.