Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

How to Rename Files and Directories in Python with os.rename() – Step-by-Step Guide

Renaming Files and Directories in Python

Python’s os.rename() function provides a simple, cross‑platform way to rename files or directories. Whether you’re cleaning up naming conventions or updating project assets, mastering this method is essential for efficient file handling.

Syntax

os.rename(src, dst)

Parameters

src: The existing path of the file or directory you wish to rename. It must exist before the call.

dst: The new path (or just the new name if staying in the same directory). This will be the file or directory’s new name.

Example

import os
os.rename('guru99.txt', 'career.guru99.txt')

In this example, the original file guru99.txt is renamed to career.guru99.txt within the same directory.

How to Rename Files and Directories in Python with os.rename() – Step-by-Step Guide

Full Working Code

import os
from os import path

def main():
    # Ensure the source file exists
    if path.exists('guru99.txt'):
        # Resolve the absolute path (optional)
        src = path.realpath('guru99.txt')
        # Perform the rename
        os.rename('guru99.txt', 'career.guru99.txt')

if __name__ == "__main__":
    main()

Handling Errors

Always guard against potential errors such as FileNotFoundError or PermissionError. Wrapping the rename call in a try/except block ensures your script fails gracefully:

try:
    os.rename(src, dst)
except FileNotFoundError:
    print(f"Source file {src} not found.")
except PermissionError:
    print("Permission denied.")
except Exception as e:
    print(f"Unexpected error: {e}")

Python

  1. Python Keywords and Identifiers: Mastering Reserved Words and Naming Conventions
  2. Python Statements, Indentation, and Comments: A Clear Guide
  3. Python Namespaces & Variable Scope: Understanding Names, Bindings, and Scopes
  4. Python File I/O: Mastering File Operations, Reading, Writing, and Management
  5. Mastering Directory and File Operations in Python
  6. Master Python Exception Handling: try, except, else, and finally Explained
  7. Build a Remote Temperature Sensor with Raspberry Pi and Python – Step‑by‑Step Guide
  8. Checking File and Directory Existence in Python – A Practical Guide
  9. How to Read and Write CSV Files in Python: A Comprehensive Guide
  10. Accessing Web Data with Python’s urllib: A Practical Guide