Python - os.replace() method
Last Updated :
23 Sep, 2025
os.replace() method is used to rename a file or directory. If the destination already exists as a file, it will be replaced without any error, provided the user has the necessary permissions. However, if the destination is a directory, an OSError will be raised.
Note that this method may fail if the source and destination are located on different filesystems.
Syntax
os.replace(source, destination, *, src_dir_fd=None, dst_dir_fd=None)
Parameter:
- source: The name of the file or directory to be renamed.
- destination: The new name to assign to the file or directory.
- src_dir_id: (Optional) A file descriptor referring to a source directory.
- dst_dir_fd: (Optional) A file descriptor referring to a destination directory.
- Return Type: This method does not return any value.
Example 1: Renaming a File
Python
import os
f1 = "file.txt" # This is your existing file
f2 = "renamed_file.txt" # This will be the new name of the file
os.replace(f1, f2)
Explanation: This code renames the existing file file.txt to renamed_file.txt, replacing the new name if it already exists.
Example 2: Handling Errors
When renaming files, errors can occur if the source or destination is invalid, or if the program lacks the necessary permissions. The try-except blocks handle issues such as permission errors, type mismatches, or other OS-related problems.
Python
import os
f1 = './file.txt' # current file location/name
f2 = './file_new.txt' # file name/location after renaming
try:
os.replace(f1, f2) # attempt to rename the file
print("Source path renamed to destination path successfully.")
except IsADirectoryError:
print("Source is a file, but destination is a directory.")
except NotADirectoryError:
print("Source is a directory but destination is a file.")
except PermissionError:
print("Operation not permitted.")
except OSError as error:
print(f"Some other error occurred: {error}")
Explanation: The code tries to rename the file from f1 to f2. If errors occur (e.g., permission issues, or mixing files and directories), they are caught using try-except blocks, so the program does not crash.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice