How to Move a File in Python [Step by Step Guide]

How to Move a File in Python [Step by Step Guide]

In this tutorial, we will learn about how to move a file in Python using step by step guide. In any programming language, transferring data from one path to another is a common operation. Every programming language provides its own set of modules and methods to do the file transfer operation. Python also provides several modules that helps us to transfer the data from one path to another in our system. We will cover few commonly used modules in Python for file transfer operation. So let’s get started.

 

How to Move a File in Python [Step by Step Guide]

There are several built-in modules available in Python which provides the classes to perform file transfer operation on the system. The most commonly used modules which we will cover in this tutorial are os, shutil and pathlib module. All three modules provides classes that has the capability to copy the file from source path to destination independent of operating system.

 

Using OS Module

‘os’ module is Python’s standard library module that provides a way to interact with the operating system including files and directories operations.  There are several classes available in OS module. We will use two classes available in OS module i.e  rename() and replace(). Both helps in transferring files from one path to another.

Example-1 :  os.raname() 

rename() class takes two argument, source file path and destination file  path. It copy the files in the destination path supplied. Once copy is done, it will delete the file from source path. It does the same process for directory transfer as well as shown in below examples.

#!/usr/bin/python3
import os,sys

source_file_path = "/root/gert/hello-python"
dest_file_path = "/tmp/backup/hello-python"

try:
os.rename(source_file_path, dest_file_path)
print("File copy using os.rename() is successful")
print(os.listdir('/tmp/backup'))

except Exception as e:
print(f"Error: {e}")

sys.exit(0)

OUTPUT

File copy using os.rename() is successful
['hello-python']

 

 

Example-2: os.replace()

replace() class also copies the files and directories from source path to destination path. Unlike rename() method, it does not delete the file/directory from source path after copying the file.

#!/bin/python3
import os,sys

source_dir_path = "/root/gert/python-dump"
dest_dir_path = "/tmp/backup/python-dump"

try:
os.replace(source_dir_path, dest_dir_path)
print("Directory copy using os.replace() is successful")
print(os.listdir('/tmp/backup'))

except Exception as e:
print(f"Error: {e}")

sys.exit(0)

OUTPUT

Directory copy using os.replace() is successful
['python-dump']

 

Using Shutil Module

shutil is a standard Python module that provides a higher-level interface for file operations. It can be used to copy files and directories. It provides move() class to copy and move the file from one path to another. Its behavior is same as os.rename() function. There is only difference between these two, os.rename() does not work if source file path and destination file path are on different disk. In such case,  shutil.move() comes in picture as shutil.move() is files disk agnotic.

Example-3: shutil.move()

move() class copy the file from source path to destination path. It deletes the file from source path after copying to destination path.

#!/bin/python3
import shutil,sys

source_dir_path = "/root/gert/python-dump"
dest_dir_path = "/tmp/backup/python-dump"

try:
shutil.move(source_dir_path, dest_dir_path)
print("Directory copy using shutil.move() is successful")
print(os.listdir('/tmp/backup'))

except Exception as e:
print(f"Error: {e}")

sys.exit(0)

OUTPUT

Directory copy using shutil.move() is successful
['python-dump']

 

Example-4: shutil.copy()

copy() class copy the file from source path to destination path without deleting the file at source path.

#!/usr/bin/python3
from shutil import copy
import sys,os

source_dir_path = "/root/gert/hello-python"
dest_dir_path = "/tmp/backup/hello-python"

try:
copy(source_dir_path, dest_dir_path)
print("File copy using shutil.copy() is successful")
print(os.listdir('/tmp/backup'))

except Exception as e:
print(f"Error: {e}")

sys.exit(0)

OUTPUT

File copy using shutil.copy() is successful
['hello-python']

 

Example-5: shutil.copytree()

copytree() class recursively copy a directory and its contents to the destination path. Let us implement copytree() class in below code to copy the directory. We have created a new directory ‘python-dump’ in source path which has two files inside it, file1.txt, file2.txt.

#!/usr/bin/python3
from shutil import copytree
import sys,os

source_dir_path = "/root/gert/python-dump"
dest_dir_path = "/tmp/backup/python-dump"

try:
copytree(source_dir_path, dest_dir_path)
print("Directory copy using shutil.copytree() is successful")
print(os.listdir('/tmp/backup'))

except Exception as e:
print(f"Error: {e}")

sys.exit(0)

OUTPUT

Directory copy using shutil.copytree() is successful
['python-dump']

 

Using Pathlib Module

pathlib is a standard Python module that provides classes to perform file transfer operation on different operating systems. pathlib.Path class was introduced in Python3.4 for object oriented filesystem path manipulation. It offeres an intutive and convenient way to work with file and directory paths in a platform independent manner.

Example-6: pathlib.Path()

Path() class provide rename() method to copy the file on destination path. Let us implement this class in below code to copy the file.

#!/usr/bin/python3
from pathlib import Path
import sys,os

source_dir_path = "/root/gert/hello-python"
dest_dir_path = "/tmp/backup/hello-python"

try:
Path(source_dir_path).rename(dest_dir_path)
print("File transferred using pathlib.Path() class is successful")
print(os.listdir('/tmp/backup'))

except Exception as e:
print(f"Error: {e}")

sys.exit(0)

OUTPUT

File copy using pathlib.Path() class is successful
['hello-python']

 

Summary

Read more about Python modules from python.org 

 

Leave a Comment