Friday, December 27, 2024
Google search engine
HomeLanguagesCopy all files from one directory to another using Python

Copy all files from one directory to another using Python

In this article, we will discuss how to copy all files from one directory to another using Python.

This can be done using the shutil module. This module can be used in Python to perform operations on files and folders in a directory. Shutil package facilitates the access, movement, and removal of the files between directories.

Method 1 : Using shutil.copytree() 

The shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. It is used to recursively copy a file from one location to another. The destination should not be an existing directory. It is created during the copy operation execution. 

Syntax: shutil.copytree(src, dst, copy_function = copy2)

Parameter: 

  • src : source directory
  • dst : destination director
  • copy_function (optional): Default – copy2(). copy() method may also be used.

Returns :The newly created destination directory name

Extended support for the os package is also needed in Python to perform all the operations related to file manipulations effectively. It provides many functions to work with directories, and their corresponding files and folders contained. 

os.listdir(dir), lists all the files in the specified directory, dir, and os.path.join(a, b) is used to create a path by joining sub-paths a followed by b respectively. 

Directory in use: 

Python3




import shutil
import os
 
# path to source directory
src_dir = 'fol1'
 
# path to destination directory
dest_dir = 'fol2'
 
# getting all the files in the source directory
files = os.listdir(src_dir)
 
shutil.copytree(src_dir, dest_dir)


Output:

Method 2 : Using shutil.copy2()

The copy2() method in Python is used to copy the content of the source file to the destination file or directory. This method is identical to shutil.copy() method also preserving the file’s metadata. 

Syntax:

shutil.copy2(src, dst)

Parameter:

  • src : source directory
  • dst : destination director

Returns: The destination directory path 

In addition to this, the Pathlib module is also incorporated to work with filesystem paths concerned with different operating systems. The Path function in the Pathlib package is used to define concrete paths. 

Note: In this method, the files are copied to an already existing folder.

Directory in use: 

Python3




# importing required packages
from pathlib import Path
import shutil
import os
 
# defining source and destination
# paths
src = 'source'
trg = 'destination'
 
files=os.listdir(src)
 
# iterating over all the files in
# the source directory
for fname in files:
     
    # copying the files to the
    # destination directory
    shutil.copy2(os.path.join(src,fname), trg)


Output:

RELATED ARTICLES

Most Popular

Recent Comments