0
0
PythonHow-ToBeginner · 3 min read

How to Rename a File in Python: Simple Guide

To rename a file in Python, use the os.rename() function from the os module. Provide the current file name and the new file name as arguments to this function.
📐

Syntax

The syntax to rename a file in Python is simple. You use the os.rename() function which takes two arguments:

  • src: The current name or path of the file you want to rename.
  • dst: The new name or path you want the file to have.

Make sure to import the os module before using this function.

python
import os

os.rename(src, dst)
💻

Example

This example shows how to rename a file named old_file.txt to new_file.txt. It demonstrates importing the os module and calling os.rename() with the correct arguments.

python
import os

# Rename 'old_file.txt' to 'new_file.txt'
os.rename('old_file.txt', 'new_file.txt')

print('File renamed successfully.')
Output
File renamed successfully.
⚠️

Common Pitfalls

Some common mistakes when renaming files in Python include:

  • Not importing the os module before calling os.rename().
  • Using incorrect file paths or names that do not exist, which causes a FileNotFoundError.
  • Trying to rename a file to a name that already exists, which can overwrite files without warning.
  • Not having the right permissions to rename the file, causing a PermissionError.

Always check that the source file exists and that you have permission to rename it.

python
import os

# Wrong: forgetting to import os
# rename('old.txt', 'new.txt')  # NameError: name 'rename' is not defined

# Right way:
os.rename('old.txt', 'new.txt')
📊

Quick Reference

FunctionDescriptionExample
os.rename(src, dst)Renames a file or directory from src to dstos.rename('file1.txt', 'file2.txt')
os.path.exists(path)Checks if a file or directory existsos.path.exists('file1.txt')
os.remove(path)Deletes a fileos.remove('file.txt')

Key Takeaways

Use os.rename(src, dst) to rename files in Python.
Always import the os module before using os.rename().
Check that the source file exists to avoid errors.
Be careful not to overwrite existing files unintentionally.
Handle permissions to avoid PermissionError when renaming.