简体   繁体   English

无法将文件从文件夹复制到不同的文件夹

[英]Trouble copying files from folder to different folders

I'm trying to loop over the files witch start with 'R008' in the directory and copy them to the different folders (which are all in the same directory).我正在尝试遍历目录中以“R008”开头的文件,并将它们复制到不同的文件夹(都在同一目录中)。

import shutil
import os
source = 'D:\\source_folder\\'
dest1 = 'D:\\destination_folder\\' 

folder_name = input("What day of the month? ")
folder_path = (dest1 + folder_name)
i = 1

files = os.listdir(source)

for file in files:
    if file.startswith('R008'):
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)
            shutil.copy(os.path.join(source, file), folder_path)

        if os.path.exists(folder_path):
            os.makedirs(folder_path + "_" + str(i))
            shutil.copy(os.path.join(source, file), folder_path + "_" + str(i))
            i += 1

My problem is the first file is always copied twice.我的问题是第一个文件总是被复制两次。 5 folders are created for 4 files 1 .为 4 个文件创建 5 个文件夹1 And I don't understend why我不明白为什么

You have two independent tests, and the body of the first if makes (by creating folder_path ) the condition for the second if ( folder_path exists) true.您有两个独立的测试,第一个if的主体(通过创建folder_path )使第二个iffolder_path存在)的条件为真。 So you end up performing both copies.所以你最终执行了两个副本。 If you want to only copy to the root path, and not also copy to the extended path, just make the second if into an else tied to the original if , eg:如果您只想复制到根路径,而不想复制到扩展路径,只需将第二个if放入与原始if绑定的else ,例如:

    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
        shutil.copy(os.path.join(source, file), folder_path)
    else:  # Could be elif os.path.exists(folder_path), but you literally just verified it doesn't exist
        os.makedirs(folder_path + "_" + str(i))
        shutil.copy(os.path.join(source, file), folder_path + "_" + str(i))
        i += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM