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