简体   繁体   English

将文件从一个文件夹复制到另一个文件夹(而不是覆盖)

[英]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.

相关问题 将(文件)名称末尾带有特定文本的文件从一个文件夹复制到另一个文件夹 - Copy files with specific text at the end of their (file) names from one folder to other folder 如何使用字典将文件从一个文件夹复制到多个其他文件夹 - How to copy files from one folder to multiple other folders using a dictionary 如何从文件夹到文件夹复制一百个文件? - How to copy one hundred files from folder to folder? 将多个文件从子文件夹复制到一个文件夹 - Copy multiple files from sub folder into one folder 如何将奇数文件从一个文件夹复制到另一个文件夹? - How to copy odd numbered Files from one folder to another folder? 将文件从一个文件夹复制到另一个文件夹并重命名文件 - Copy files from one folder to another and rename the files 使用python将某些文件复制到另一个文件夹 - Copy certain files from one folder to another using python 将粘贴文件从不同目录复制到一个文件夹 - copy paste files from different directories to one folder 从一个文件夹中随机选择文件并递归复制到子文件夹中 - Random selection of files from one folder and recursively copy them into subfolders 将文件从一个文件夹复制到另一个在 .txt 文件中具有匹配名称的文件夹 - Copy files from one folder to another with matching names in .txt file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM