Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Python

Python os.rename(): Renaming a File or Directory

  • 26 Jul, 2025
  • Com 0
Python os.rename() Method

The os.rename() is a built-in Python function that renames a source directory or a file to a specified destination directory or file. It is a cross-platform function that allows moving files or directories to a new location within the same filesystem.

Syntax

os.rename(src, dst, src_dir_fd=None, dst_dir_fd=None)

Parameters

Argument Description
src (str or bytes) It represents a current directory path whose file or directory is to be renamed.
dst (str or bytes) It represents a new file or directory path.
src_dir_fd (int, optional)

It is a file descriptor referring to a directory, used as the base for src (Unix only).

dst_dir_fd (int, optional)

It is a file descriptor referring to a directory, used as the base for dst (Unix only).

Renaming a file

We can rename a file by passing the path of the old file and the path of the new file.

Here is the current state of the file before renaming:

Before renaming a file

As you can see from the above screenshot that we have a file called “file.txt”. We will rename it to “new_file.txt”.

import os

# Renaming 'file.txt' to 'new_file.txt'
os.rename('dir1/file.txt', 'dir1/new_file.txt')

print("File renamed successfully.")

# Output: File renamed successfully.

After renaming a file using os.rename() method

What if new_file.txt already exists? Well, this behavior depends on the OS (Unix: overwrite; Windows: error).

Moving and renaming a file

The os.rename() function not only renames a file but also moves it to a different directory with a specified name. Let’s say we have a file called new_file.txt in our current directory.

Before moving a file

Let’s move the new_file.txt to a new_dir folder with the latest_file.txt file name.

import os

os.rename('dir1/new_file.txt', 'dir1/new_dir/latest_file.txt')

print("File moved successfully.")

# Output: File moved successfully.

After moving a file with a new name, the new_dir folder looks like this screenshot:

Moving and renaming a file using os.rename() method

Renaming a directory

In the current state of the file system, we have a directory named “new_dir”.

Before renaming a directory

Let’s rename an entire directory from “new_dir” to “latest_dir”.

import os

# Renaming a directory from 'new_dir' to 'latest_dir'
os.rename('dir1/new_dir', 'dir1/latest_dir')

print("Directory renamed from 'new_dir' to 'latest_dir'")

# Output: Directory renamed from 'new_dir' to 'latest_dir'

Renaming a directory using os.rename() method

Handling overwrites

When it comes to existing files, it depends on the platform you are working on. If your renamed file already exists and your platform is Unix, it will overwrite it silently. However, if your OS is Windows, it may throw an OSError.

To handle potential errors, you can use the try-except mechanism.

import os

# Unix: Overwrites 'existing.txt' silently
# Windows: Raises OSError if 'existing.txt' exists

try:
    os.rename('source.txt', 'existing.txt')
except OSError as e:
    print(f"Error: {e}")

The output will depend on the Operating System you are using.

Non-existent source

While renaming a file, if the source file does not exist, it will raise a FileNotFoundError. To handle this type of error, use a try-except block.

Non-existent source

In the dir1 directory, there is no file named not_exist.txt, yet we still attempt to rename it; this method will throw an error.

import os

try:
    os.rename('dir1/not_exist.txt', 'dir1/new.txt')
except FileNotFoundError as e:
    print(f"Error: {e}")

# Output: Error: [Errno 2] No such file or directory: 'not_exist.txt' -> 'new.txt'

Destination directory does not exist

What if you are trying to move a file and rename it to another folder, but that folder does not exist? Well, again, it will throw the error.

import os

try:
    os.rename('dir1/latest_file.txt', 'dir1/folder2/new.txt')
except FileNotFoundError as e:
    print(f"Error: {e}")

# Output: No such file or directory: 'dir1/latest_file.txt' -> 'dir1/folder2/new.txt'

That’s all!

Post Views: 76
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

How to Convert NumPy Array of Floats to an Array of Integers
Python "-m" flag Example and How to Use It

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend