fbpx

Python Script to Copy only Changed Files From one Dir to Another

Here is a python script that will copy only changed files from one directory to another:

				
					import os
import shutil

# source directory
src = r"C:\Users\Administrator\Downloads\fold"

# destination directory
dst = r"C:\Users\Administrator\Downloads\foldc"

# copy changed files
for item in os.listdir(src):
    s = os.path.join(src, item)
    d = os.path.join(dst, item)
    if os.path.isdir(s):
        continue
    if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1:
        shutil.copy2(s, d)
				
			

This script will copy files from the source directory to the destination directory if they do not already exist in the destination directory, or if they have been modified more recently than the version in the destination directory. It uses the shutil module’s copy2() function to copy the files.

Note that this script will not copy directories, and it will not handle errors, such as if the destination directory does not exist or if the user does not have permission to write to the destination directory. You may want to add error handling and additional functionality to the script to handle these cases.

Script to copy both Files and Folders

				
					import os
import shutil

# source directory
src = r'C:\Users\Administrator\Downloads\fold'

# destination directory
dst = r'C:\Users\Administrator\Downloads\foldc'

# copy changed files and directories
for item in os.listdir(src):
    s = os.path.join(src, item)
    d = os.path.join(dst, item)
    if os.path.isdir(s):
        if not os.path.exists(d):
            shutil.copytree(s, d)
        else:
            for f in os.listdir(s):
                sf = os.path.join(s, f)
                df = os.path.join(d, f)
                if os.path.isdir(sf):
                    continue
                if not os.path.exists(df) or os.stat(sf).st_mtime - os.stat(df).st_mtime > 1:
                    shutil.copy2(sf, df)
    else:
        if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1:
            shutil.copy2(s, d)

				
			

Share:

Facebook
Twitter
Pinterest
LinkedIn

Social Media

Most Popular

Get The Latest Updates

Subscribe To Our Weekly Newsletter

No spam, notifications only about new products, updates.

Categories