Python3 os.replace Method
Python3 OS File/Directory Methods
Overview
The os.replace() method renames a file or directory.
New in Python 3.3.
Syntax
The **replace()** method syntax is as follows:
os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Rename the file or directory src to dst; if dst is a non-empty directory, OSError is raised. If dst exists and is a file, it will be replaced if the user has permission.
Parameters
-
src -- the source file or directory; if that file does not exist, a FileNotFoundError error is raised.
-
dst -- the file or directory after renaming; if it already exists, it is replaced directly.
-
src_dir_fd -- a path relative to a directory descriptor.
-
dst_dir_fd -- a path relative to a directory descriptor.
Return Value
If it succeeds, the rename is an atomic operation (as required by POSIX); on failure it returns OSError.
Example
The following example demonstrates the use of the replace() method:
The content of the text file google.txt is:
google
Example
import
os
Rename a file or directory
os
.
replace
(
'google.txt'
,
'runoob.txt'
)
After execution only runoob.txt remains, with the content:
google
If the replaced file dst already exists, it will be overwritten:
The content of the text file test1.txt is:
google
The content of the text file test2.txt is:
runnob
Example
import
os
Rename a file or directory
os
.
replace
(
'test1.txt'
,
'test2.txt'
)
After execution only test2.txt remains, with the content:
google