Easy Tutorial
❮ Python String Isdecimal Python Min List Element ❯

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

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

Python3 OS File/Directory Methods

❮ Python String Isdecimal Python Min List Element ❯