我正在尝试让我的程序从文件(例如.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)
更新-运行无误,但不会移动任何文件。
答案 0 :(得分:1)
程序的最后部分可能会通过以下方式更好地工作:
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
。
btw,file
是python中的保留字,我建议为您的变量使用另一个名称,该名称与python保留字不符。
答案 1 :(得分:1)
您的上一节有问题。
for file in os.listdir(folderPath):
for file in files:
if file in filesToFind:
shutil.copy(file, destination)
第一个for
循环遍历目录中的每个文件名,这是完全可以理解的。
第二个for
是一个错误,因为files
不存在。您打算怎么办?
答案 2 :(得分:1)
有效的代码-
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的帮助!是时候对其进行完善以使其更加人性化了