[英]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)
You could simply add a check before your copy:您可以简单地在您的副本之前添加一个检查:
if not os.path.exists(d):
shutil.copy(s, d)
You can simply use shutil which gives huge amount of choices in order to file operations.您可以简单地使用shutil,它提供了大量的选择来进行文件操作。 Check the documentation here
检查文档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.
我已经测试过它并且它在我的系统中工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.