我正在尝试循环遍历目录中以“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个文件夹。我不明白为什么
您有两个独立的测试,第一个
if
的主体(通过创建folder_path
)使第二个if
(folder_path
存在)的条件为true。因此,您最终执行两个副本。如果只想复制到根路径,而不想复制到扩展路径,只需将第二个if
复制到与原始if
绑定的else
,例如:相关问题 更多 >
编程相关推荐