os.rename() method in Python renames a file or directory by changing its name or path. It belongs to the built-in os module and can also move a file or directory to another location on the same filesystem.
Following example renames old.txt to new.txt. Create old.txt in the current working directory before running the program, and ensure new.txt does not already exist.
import os
os.rename("old.txt", "new.txt")
print("File renamed successfully")
Output
File renamed successfully
Explanation:
- os.rename() changes the file's name from old.txt to new.txt.
- File's contents remain unchanged.
- Source file must exist, and the destination must be valid.
Syntax
os.rename(src, dst)
Parameters:
- src: Existing path of the file or directory.
- dst: New name or destination path.
Both arguments accept path strings or path-like objects. The method does not create missing parent directories automatically.
Example 2: Renaming a Directory
import os
os.rename("old_folder", "new_folder")
print("Directory renamed successfully")
Output
Directory renamed successfully.
Explanation:
- Existing directory old_folder receives the new name new_folder.
- Files and subdirectories remain inside the renamed directory.
- Operation can fail if the paths are invalid or filesystem restrictions prevent the change.
Example 3: Moving a File Another Directory
Destination path can include a different directory, allowing the file to be renamed and relocated in one operation. Both parent directories must already exist.
import os
src = os.path.join("reports", "january.txt")
dst = os.path.join("archive", "january.txt")
os.rename(src, dst)
print("File moved successfully")
Output
File moved successfully
Explanation:
- os.path.join() builds paths using the appropriate separator for the operating system.
- File moves from reports to archive without changing its filename.
- Source and destination must be on the same filesystem for this operation to work reliably.
- Use shutil.move() when cross-filesystem movement is required.
Example 4: Handling Errors During Renaming
Renaming may fail because the source does not exist, permissions are insufficient, or the destination conflicts with an existing path. A try-except block lets the program handle these failures instead of terminating unexpectedly.
import os
try:
os.rename("old.txt", "new.txt")
print("File renamed successfully")
except FileNotFoundError:
print("Source file or directory was not found.")
except FileExistsError:
print("Destination already exists.")
except PermissionError:
print("Permission denied.")
except OSError as error:
print(f"Rename failed: {error}")
Output
Source file or directory was not found.
Explanation:
- FileNotFoundError handles missing source paths or required path components.
- FileExistsError handles destination conflicts when the operating system raises that exception.
- PermissionError handles insufficient permissions.
- OSError catches other filesystem-related failures not handled by the preceding exceptions.