Python3 os.replace Method
Python3 OS File/Directory Methods
Overview
The os.replace() method is used to rename a file or directory.
New in version Python3.3.
Syntax
The syntax for the replace() method is as follows:
os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Renames the file or directory src to dst. If dst is a non-empty directory, an OSError is raised. If dst exists and is a file, it will be replaced if the user has the necessary permissions.
Parameters
src-- The source file or directory. If this directory file does not exist, aFileNotFoundErroris raised.dst-- The renamed file or directory. If it already exists, it will be replaced directly.src_dir_fd-- The path of the relative directory descriptor.dst_dir_fd-- The path of the relative directory descriptor.
Return Value
If successful, the renaming is an atomic operation (as required by POSIX), and an OSError is returned if it fails.
Example
The following example demonstrates the use of the replace() method:
The content of the file google.txt is:
google
Example
import os
# Rename file or directory
os.replace('google.txt', 'tutorialpro.txt')
After execution, only tutorialpro.txt remains, with the content:
google
If the destination file dst already exists, it will be replaced:
The content of the file test1.txt is:
google
The content of the file test2.txt is:
runnob
Example
import os
# Rename file or directory
os.replace('test1.txt', 'test2.txt')
After execution, only test2.txt remains, with the content:
google