Python-将特定文件从列表复制到新文件夹中

标签 python python-3.x tkinter copy-paste shutil

我试图让我的程序从文件(例如.txt)中读取名称列表,然后在选定的文件夹中搜索这些文件,并将这些文件复制并粘贴到另一个选定的文件夹中。我的程序运行没有错误,但没有执行任何操作:

代码 - 更新:

import os, shutil
from tkinter import filedialog
from tkinter import *


root = Tk()
root.withdraw()

filePath = filedialog.askopenfilename()
folderPath = filedialog.askdirectory()
destination = filedialog.askdirectory()

filesToFind = []
with open(filePath, "r") as fh:
    for row in fh:
        filesToFind.append(row.strip())

#Added the print statements below to check that things were feeding correctly
print(filesToFind)
print(folderPath)
print(destination)

#The issue seems to be with the copy loop below:    
for target in folderPath:
    if target in filesToFind:
        name = os.path.join(folderPath,target)
        print(name)
        if os.path.isfile(name):
            shutil.copy(name, destination)
        else:
            print ("file does not exist", name)
        print(name)

更新 - 运行时没有错误,但不移动任何文件。

最佳答案

程序的最后一部分可能会以这种方式运行得更好:

for file in files:
    if file in filesToFind:
        name = os.path.join( folderPath, file )
        if os.path.isfile( name ) :
            shutil.copy( name, destination)
        else :
            print 'file does not exist', name

否则,几乎不知道您从哪里复制文件,也许是当前文件夹,如果您不使用它,为什么需要提前输入 folderPath

顺便说一句,file是Python中的保留字,我建议您为变量使用另一个名称,该名称与Python保留字不一致。

关于Python-将特定文件从列表复制到新文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51528103/

相关文章:

python - 从系列创建数据帧时保持列顺序

python - 如何在 Django 中的多对多关系中向数据透视表添加更多列?

python - 如何在点击时获取最接近的 tkinter Canvas 元素?

python - 将 ttk 笔记本选项卡设置在中心 [Python]

python - 添加多个条目并从中动态检索数据

python - 统一码编码错误 : 'ascii' codec can't encode character u'\xe9'

python - Pyramid 架构迁移

Python:heapq.heappop() 给出奇怪的结果

Python qtConsole 和 Spyder : Problems with loading modules

python - 将 Django 电子邮件打印到控制台时出现问题