Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy files from one folder to other (and not overwrite)

Tags:

python

os.walk

I am using the following code to copy files from one folder to other, but files are getting overwritten, is there anyway to copy files to a new sub folder for each iteration ?

for patients in parent:
    for root, dirnames, filenames in os.walk(patients):
        for filename in fnmatch.filter(filenames, '*.dcm'):
            matches.append(os.path.join(root, filename))

            s=os.path.join(root, filename)
            d =os.path.join(dst, filename)
            shutil.copy(s, d)
like image 773
Stefann Avatar asked Oct 23 '25 11:10

Stefann


2 Answers

You could simply add a check before your copy:

if not os.path.exists(d):
   shutil.copy(s, d)
like image 194
Oliver.R Avatar answered Oct 26 '25 01:10

Oliver.R


You can use the function shutil.copytree() and pass in a customized copy_func:

def copy_func(src, dst):
    if os.path.isdir(dst):
        dst = os.path.join(dst, os.path.basename(src))
    if os.path.exists(dst):
        # don't override if already file existed
        # keep both versions instead
        os.rename(dst, f'{dst}-backup')
    shutil.copy2(src, dst)

shutil.copytree(src, dest, dirs_exist_ok=True, copy_function=copy_func)
like image 30
Arthur Avatar answered Oct 26 '25 01:10

Arthur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!