---Advertisement---

Python File and Directory Renaming Using os.rename() with Best Examples 2025

By Bhavani

Updated On:

---Advertisement---
Python File and Directory Renaming

Python File and Directory Renaming: Renaming files and directories in Python is simple with the os.rename() method. This method is part of Python’s built-in os module, designed to manage file operations effectively.


The os.rename() method allows you to rename files or directories by specifying the source (current file name) and destination (new file name).

python

os.rename(src, dst)

  • src: The current name of the file or directory. The file must already exist.
  • dst: The new name for the file or directory.

Let’s understand the process with a clear example.

python

import os

from os import path

def main():

    # Check if the file exists

    if path.exists(“Software Moji Moji.txt”):

        # Rename the file

        os.rename(‘Software Moji Moji.txt’, ‘career.Software Moji Moji.txt’)

        print(“File renamed successfully!”)

if __name__ == “__main__”:

    main()

โœ… The code first checks if the file “Software Moji Moji.txt” exists.
โœ… If the file is present, it renames it to “career.Software Moji Moji.txt” using os.rename().
โœ… On successful execution, the new file name will appear in your directory.

arduino

File renamed successfully!


โœ… The source file (src) must exist; otherwise, the code will raise a FileNotFoundError.
โœ… The destination (dst) must not exist; otherwise, Python will overwrite the existing file.
โœ… Ensure you have the necessary permissions to modify the file or directory.


The os.rename() method can also rename folders (directories) in Python.

python

import os

# Renaming a folder

os.rename(‘Old_Folder’, ‘New_Folder’)

print(“Directory renamed successfully!”)


To avoid unexpected errors, use a try-except block for better control.

python

import os

try:

    os.rename(‘Old_File.txt’, ‘New_File.txt’)

    print(“File renamed successfully!”)

except FileNotFoundError:

    print(“Error: The specified file does not exist.”)

except PermissionError:

    print(“Error: Insufficient permissions to rename the file.”)

except Exception as e:

    print(f”An error occurred: {e}”)


โœ… Use os.rename() to efficiently rename files and directories.
โœ… Handle errors using try-except to prevent unexpected issues.
โœ… Ensure the source file exists and the destination file does not conflict with existing files.

Python Copy File Methods

Download Python

Leave a Comment

Index