How to Move a File in Python

Created
Modified

Using os Module

The os.rename() method renames the file or directory src to dst. If dst exists, the operation will fail with an OSError subclass in a number of cases:

#!/usr/bin/python3

# Import module
import os

os.rename("file.txt", "file.1.txt")

os.replace("file.1.txt", "file.txt")
file.1.txt

Using shutil.move Method

Recursively move a file or directory (src) to another location (dst) and return the destination.

#!/usr/bin/python3

# Import module
import shutil

shutil.move("file.txt", "file.1.txt")
file.1.txt

Using pathlib Module

After Python 3.4, you can also use pathlib's class Path to move file.

#!/usr/bin/python3

# Import module
import pathlib

pathlib.Path("file.txt").rename("file.1.txt")
file.1.txt

Related Tags

#move# #file#