Stefann
Stefann

Reputation: 135

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

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)

Upvotes: 4

Views: 3791

Answers (3)

Arthur
Arthur

Reputation: 51

You can use shutil.copytree method, 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)

Upvotes: 2

mrconcerned
mrconcerned

Reputation: 1945

You can simply use shutil which gives huge amount of choices in order to file operations. Check the documentation here

Code:

import os
import shutil
spath='C:/Path/to/Source'
sfiles = os.listdir(spath)
dpath = 'C:/Path/to/Destination'
for file in sfiles:
if file.endswith('.dcm'):
   shutil.copy(os.path.join(spath,file), os.path.join(dpath,file))

If you have questions and if it doesn't work, please comment below. I have tested it and it works in my system.

Upvotes: 1

Oliver.R
Oliver.R

Reputation: 1368

You could simply add a check before your copy:

if not os.path.exists(d):
   shutil.copy(s, d)

Upvotes: 4

Related Questions