Python os.replace() Method

Python os.replace() Method

  1. Syntax of the os.replace() Method
  2. Example Codes: Usage of the os.replace() Method in Python
  3. Example Codes: OSError Exception While Using the os.replace() Method in Python
  4. Example Codes: os.replace() vs os.rename() Method in Python
  5. Example Codes: Handle Possible Errors With the os.replace() Method in Python
  6. Example Codes: os.replace() Method With the Access is denied Error in Python

The os.replace() method is used in Python to rename a file. If the source is a directory, the destination should also be a directory; likewise, if the source is a file address, the destination should also be a file address.

The method os.replace() will return an OSError if the source and destination are not the same as mentioned above. The OSError will also occur if the source and destination are on different filesystems.

Syntax of the os.replace() Method

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

Parameters

src This is the source file we want to rename.
dst This is the destination name to be given to the newly renamed file.
src_dir_fd (optional) This is the source file directory.
dst_dir_fd (optional) This is the destination file directory.

Return

This method only changes the name of the given source file and copies it to the destination path but does not return any value.

Example Codes: Usage of the os.replace() Method in Python

We must import the OS module to use the os.replace() method. The os.replace() method uses the two necessary parameters: source and destination.

Remember, the source and destination are on the same path. The rest of the parameters are optional and is not necessary to pass as a parameter.

# importing os module
import os
#source and destination file on same path
source_file = "myFile.txt"
dest_location = "myRenamedFile.txt"
#method to have newly renamed file
os.replace(source_file, dest_location)
#print success message on renaming myFile.txt to myRenamedFile.txt
print("File is renamed successfully.")

Output:

File is renamed successfully.
#this message will be displayed upon successful execution of code

Similarly, if we want the same file to be renamed in a different directory, the source remains the same, and the destination is in a different folder. Let’s take this example to elaborate further.

import os

source_file = "myFile.txt"
#the destination contains the directory and name of the file
dest_location = "Junaid\myRenamedFile.txt"

os.replace(source_file, dest_location)
#success message
print("File is renamed successfully.")

Output:

File is renamed successfully.

Example Codes: OSError Exception While Using the os.replace() Method in Python

In this method, if we want to rename a file to a new filesystem (another directory), then the os.replace() method will return the OSError exception.

import os
#this file is in the main C drive
source_file = "myFile.txt"
#destination is pointing towards another drive, i.e., E drive
dest_location = "E:\myRenamedFile.txt"

os.replace(source_file, dest_location)
print("File is renamed successfully.")

Output:

OSError: The system cannot move the file to a different disk drive: 'myFile.txt' -> 'E:\\myRenamedFile.txt'

Example Codes: os.replace() vs os.rename() Method in Python

We see that in the os.replace() method, we have renamed the file by passing the source and destination parameters. Similarly, we have the os.rename() method, which can also rename the file.

But, the only difference is that in os.rename(), when the destination file already exists, it will show a FileExistsError as an output.

Now let’s code both the methods in the same program to evaluate the difference.

import os

source_file = "myFile.txt"
dest_location = "Junaid\myNewFile.txt"
#replace method
os.replace(source_file, dest_location)
print("File is renamed successfully.")
#rename method
os.rename(source_file, dest_location)
print("File is renamed successfully.")

Output:

File is renamed successfully.
FileExistsError: Cannot create a file when that file already exists: 'myFile.txt' -> 'Junaid\\myFile.txt'

If we see the output, we can observe that with os.replace(), it will rename the file and override the same file if it already exists. But the os.rename() method will show an error if the file is already there.

Example Codes: Handle Possible Errors With the os.replace() Method in Python

In this example, we will see how we can handle different error exceptions with the os.replace() method depending on the source and destination inputs. We will check exceptions by the use of try and catch.

In the following program, the IsADirectoryError exception occurs when the source is a file and the destination is a directory. NotADirectoryError exception occurs when the source is a directory, and the destination is a file.

PermissionError exception occurs for any permission omission, and OSError occurs when there is an exception other than the ones mentioned above.

import os

#source and destination file paths
source = '.myfile.txt'
dest = '.myNewFile.txt'
#exception handling with try/catch
try:
     os.replace(source, dest)
     print("File is renamed successfully.")
#when source and destination are different formats
except IsADirectoryError:
     print("source is a file, but the destination is a directory exception.")

except NotADirectoryError:
     print("source is a directory, but the destination is a file exception.")

except PermissionError:
     print("Permission exception.")
#for remaining exceptions
except OSError as error:
    print("Other errors")

Output:

File is renamed successfully.
#if this is your output, your code is free of any of the above exceptions.

Example Codes: os.replace() Method With the Access is denied Error in Python

In the os.replace() method, sometimes there is a possibility that we might face an Access is denied error, which is a permission exception. This situation happens when the destination file path is in a read-only mode.

To access the destination file path, we need to uncheck the read-only attribute from the file properties. In the following example, you can see this type of access denied output in the console.

import os
#source and destination file
source_file = "myFile.txt"
dest_location = "Junaid\myRenamedFile.txt"

os.replace(source_file, dest_location)
print("File is renamed successfully.")

Output:

PermissionError: Access is denied: '\\Junaid'
Author: Junaid Khan
Junaid Khan avatar Junaid Khan avatar

Hi, I'm Junaid. I am a freelance software developer and a content writer. For the last 3 years, I have been working and coding with Python. Additionally, I have a huge interest in developing native and hybrid mobile applications.

LinkedIn

Related Article - Python OS

  • Python os.set_handle_inheritable() Method
  • Python os.set_inheritable() Method
  • Python os.stat_result Class
  • Python os.renames() Method
  • Python os.get_handle_inheritable Method
  • Python os.get_inheritable Method