Python os.replace() Method

Python os.replace() method is used to rename or move a file or directory, potentially overwriting the destination. If the destination file or directory exists, it will be replaced silently without any confirmation prompt.

This method can fail when the source and destination paths are on different filesystems. This limitation is due to how file systems handle file and directory operations.

Syntax

os.replace(src, dst, src_dir_fd=None, dst_dir_fd=None)

Parameters

Name Description
src (string) It is the path to the file or directory you want to rename.
dst (string) It is a new name or path for the file or directory. This is the destination path. If “dst” exists, the operation will overwrite it, provided there are sufficient permissions, and it’s not a directory (depending on the operating system).
src_dir_fd (optional) It is a file descriptor that refers to a source file or directory.
dst_dir_fd (optional) It is a file descriptor that refers to a destination file or directory.

Return value

This method does not return any value.

Example 1: Replacing a file

Before replacing a file, our directory looks like this:

Screenshot of before replacing a file

import os

# Replacing 'new_file.txt' with 'file.txt' inside 'dir1'
os.replace('dir1/new_file.txt', 'dir1/file.txt')

Output

Output of os.replace() method in Python

Example 2: Moving and replacing a file

Screenshot of moving and replacing a file

import os

# Replacing 'file.txt' file moving from 'dir1' to 'dir1/dir2'
os.replace('dir1/file.txt', 'dir1/dir2/file.txt')

Output

Screenshot of moving and replacing a file to the different directory

Example 3: Error handling

The OSError is common for issues like insufficient permissions, non-existent source paths, or issues with the destination path.

import os

try:
  # Replacing 'file.txt' with 'new_file.txt' with moving from 'dir1' to 'dir1/dir2'
  os.replace('dir1/file.txt', 'dir1/dir2/file.txt')

except IsADirectoryError:
  print("Source is a file, but the Destination is a directory.")

except NotADirectoryError:
  print("Source is a directory, but the Destination is a file.")

except PermissionError:
  print("You don't have a permission.")

except OSError as error:
  print(f"Error: {error}")

Output

Error: [Errno 2] No such file or directory: 'dir1/file.txt' -> 'dir1/dir2/file.txt'

Example 4: Replacing a directory

Screenshot of before replacing a directory

import os

try:
  # Replacing a directory
  os.replace('dir1/dir2', 'dir1/dir3')

except OSError as error:
  print(f"Error: {error}")

Output

After replacing a directory using Python os.replace()

Difference between os.rename() and os.replace()

The main difference between os.replace() and os.rename() is that the os.replace() method will unconditionally overwrite the destination file or directory if it exists, making it potentially destructive, while the os.rename() will throw the error potentially less harmful.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.