我试图让我的程序从文件(比如 .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 许可协议
有效的代码 -
注意 - 需要在正在读取的文件中包含文件扩展名。感谢@lenik 和@John Gordon 的帮助!是时候对其进行改进以使其更加用户友好