Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 os.replace() Method

Python3 os.replace Method

Python3 OS File/Directory Methods 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

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

Python3 OS File/Directory Methods Python3 OS File/Directory Methods