Open In App

Copy all files from one directory to another using Python

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Copying files from one directory to another involves creating duplicates of files and transferring them from one folder to another. This is helpful when organizing files, backing them up, or moving them to different locations on your computer. Let’s explore various methods to do this efficiently.

Using shutil.copytree()

shutil.copytree() copy an entire directory, including all its files and subdirectories, to a new location. This method recursively copies the entire directory tree, creating the destination folder if it doesn’t exist. It is ideal when you need to replicate the structure of a directory. Directory in use: 

directtory

fol1

Python
import shutil
import os

s = 'fol1'  # source directory
d = 'fol2'  # destination directory

if not os.path.exists(d):
    shutil.copytree(s, d)
else:
    print("Already exists")

Output

directory

fol 2

Explanation: This code checks if fol2 exists using os.path.exists(d). If it doesn’t exist, it uses shutil.copytree(s, d) to copy all contents of fol1 to fol2. If fol2 already exists, it prints “Already exists” to prevent overwriting.

Using shutil.copy2()

shutil.copy2() copies individual files and preserves the file’s metadata (like timestamps and permissions), unlike shutil.copy() which doesn’t retain such metadata. Directory in use: 

directtory Python
import shutil
import os

s = 'source'
t = 'destination'

files=os.listdir(s)

for fname in files:
    shutil.copy2(os.path.join(s,fname), t)

Output

directory

Explanation: os.listdir(s) retrieves a list of files and directories in the source directory, storing them in the files variable. The for loop iterates over each file name (fname) and os.path.join(s, fname) creates the full path. shutil.copy2() then copies each file to the destination directory, preserving its metadata.

Using shutil.copy()

If you don’t need to preserve metadata (like timestamps) or copy entire directory structures recursively, you can use a simpler method with os and shutil.copy() for individual files. Directory in use: 


directtory Python
import shutil
import os

s = 'source'
t = 'destination'

files = os.listdir(s)

for fname in files:
    shutil.copy(os.path.join(s, fname), t)

Output

directory

Explanation: os.listdir(s) lists all files and directories in the source directory and stores them in the files variable. The for loop iterates over each file (fname) and os.path.join(s, fname) creates the full path. shutil.copy() then copies the file content to the destination directory without preserving metadata.



Next Article
Practice Tags :

Similar Reads