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

Jas*_*nDL 6 python copy-paste tkinter shutil python-3.x

我试图让我的程序从文件(例如 .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)
Run Code Online (Sandbox Code Playgroud)

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

Jas*_*nDL 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")
Run Code Online (Sandbox Code Playgroud)

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