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

新手上路,请多包涵

我试图让我的程序从文件(比如 .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)

更新 - 运行无误但不移动任何文件。

原文由 JasonDL 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 674
2 个回答

有效的代码 -

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

root = Tk()
root.withdraw()

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

# First, create a list and populate it with the files

# you want to find (1 file per row in myfiles.txt)

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

# Had an issue here but needed to define and then reference the filename variable itself
for filename in os.listdir(folderPath):
    if filename in filesToFind:
        filename = os.path.join(folderPath, filename)
        shutil.copy(filename, destination)
    else:
        print("file does not exist: filename")

注意 - 需要在正在读取的文件中包含文件扩展名。感谢@lenik 和@John Gordon 的帮助!是时候对其进行改进以使其更加用户友好

原文由 JasonDL 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

 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 保留字不一致。

原文由 lenik 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题