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)
You could simply add a check before your copy:
if not os.path.exists(d):
shutil.copy(s, d)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With