Python3 os.replace Method

Python3 OS 文件/目录方法Python3 OS File/Directory Methods


Overview

The os.replace() method is used to rename a file or directory.

New in version Python 3.3.

Syntax

replace()The 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, an OSError will be raised. If dst exists and is a file, it will be replaced if the user has permission.

Parameters

  • src -- Source file or directory. If the file or directory does not exist, a FileNotFoundError will be raised.

  • dst -- The file or directory after renaming. If it already exists, it will be replaced directly.

  • src_dir_fd -- Path relative to directory descriptor.

  • dst_dir_fd -- Path relative to directory descriptor.

Return Value

If successful, the rename will be an atomic operation (this is a POSIX requirement). On failure, an OSError is returned.

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','example.txt')

After execution, only example.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

Python3 OS 文件/目录方法Python3 OS File/Directory Methods

Other Extensions