将文件从文件夹复制到其他文件夹时出现问题

2024-10-03 21:32:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试循环遍历目录中以“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个文件夹。我不明白为什么


Tags: 文件pathnameimport目录文件夹sourceif
1条回答
网友
1楼 · 发布于 2024-10-03 21:32:08

您有两个独立的测试,第一个if的主体(通过创建folder_path)使第二个iffolder_path存在)的条件为true。因此,您最终执行两个副本。如果只想复制到根路径,而不想复制到扩展路径,只需将第二个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

相关问题 更多 >