Python – os.replace() method
Prerequisite: OS module in Python.
os.replace() method in Python is used to rename the file or directory. If destination is a directory, OSError will be raised. If the destination exists and is a file, it will be replaced without error if the action performing user has permission. This method may fail if the source and destination are on different filesystems.
Syntax: os.replace(source, destination, *, src_dir_fd=None, dst_dir_fd=None2)
- source: Name of file or directory which we want to rename.
- destination: Name which we want to give in destination.
- src_dir_id : This parameter stores the source directory’s or file,
file descriptor referring to a directory.
- dst_dir_fd: It is a file descriptor referring to a directory,
and the path to operate. It should be relative,
path will then be relative to that directory. If
the path is absolute, dir_fd is ignored.
Return Type: This method does not return any value.
Code #1: Use of os.replace() method to rename a file.
File f.txt is renamed successfully
Code #2: Handling possible errors. (If necessary permissions are given then output will be as shown in below)
Source is a file but destination is a directory.