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.

- Use
os.rename()to renameguru99.txttocareer.guru99.txt. - After execution, the new file appears beside the original in the file explorer.
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
- Python Keywords and Identifiers: Mastering Reserved Words and Naming Conventions
- Python Statements, Indentation, and Comments: A Clear Guide
- Python Namespaces & Variable Scope: Understanding Names, Bindings, and Scopes
- Python File I/O: Mastering File Operations, Reading, Writing, and Management
- Mastering Directory and File Operations in Python
- Master Python Exception Handling: try, except, else, and finally Explained
- Build a Remote Temperature Sensor with Raspberry Pi and Python – Step‑by‑Step Guide
- Checking File and Directory Existence in Python – A Practical Guide
- How to Read and Write CSV Files in Python: A Comprehensive Guide
- Accessing Web Data with Python’s urllib: A Practical Guide