我正在尝试让我的程序从一个文件(例如.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)
更新-运行时没有错误,但不移动任何文件。
发布于 2018-08-01 04:53:03
有效的代码-
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的帮助!是时候对其进行改进,使其更加用户友好
发布于 2018-07-26 08:06:09
你程序的最后一部分可能会工作得更好:
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保留字不一致。
发布于 2018-07-26 10:49:53
你的最后一个部分有一个问题。
for file in os.listdir(folderPath):
for file in files:
if file in filesToFind:
shutil.copy(file, destination)
第一个for
循环遍历目录中的每个文件名,这是完全可以理解的。
第二个for
是错误的,因为files
不存在。你打算让它做什么?
https://stackoverflow.com/questions/51528103
复制相似问题