无法将文件从文件夹复制到其他文件夹

时间:2019-12-19 14:32:26

标签: python python-3.x

我正在尝试遍历目录中以'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

我的问题是第一个文件总是被复制两次。为4个文件1创建了5个文件夹。而且我不明白为什么

1 个答案:

答案 0 :(得分:0)

您有两个独立的测试,第一个if的主体(通过创建folder_path)使第二个if(存在folder_path)的条件成立。因此,您最终要执行两个副本。如果您只想复制到根路径,而不想复制到扩展路径,只需将第二个if放入与原始else绑定的if中,例如:

    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