【发布时间】:2018-07-25 21:42:30
【问题描述】:
我正在尝试让我的程序从文件(例如 .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)
更新 - 运行没有错误,但不移动任何文件。
【问题讨论】:
-
你想要
row.strip()而不是row.strip。注意括号。 -
for files in folderPath:没有按照你的想法做。你想要for file in os.listdir(folderPath):。 -
我将其更改为
filesToFind.append(rowstrip())和for file in os.listdir(folderPath): if file in filesToFind:但得到相同的结果(无结果) -
更新问题以包含您最近的代码。
-
已更新。抱歉仍在学习 Stack Overflow 的最佳实践
标签: python python-3.x tkinter copy-paste shutil