比较来自世界各地的卖家的域名和 IT 服务价格

Python将特定文件从列表复制到新文件夹

我正在尝试强迫我的程序从文件中读取名称列表 /说,。 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 保留的单词。

石油百科

赞同来自:

在你的最后一部分中有一个问题。


for file in os.listdir/folderPath/: 
for file in files:
if file in filesToFind:
shutil.copy/file, destination/


第一的
for

在目录中的每个文件名上停靠,这是可理解的。

第二
for

- 这是一个错误,因为
files

不存在。 你打算做什么?

风见雨下

赞同来自:

代码工作 -


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 戈登帮助到达那里! 现在是时候改进它来为用户提供更方便的时间。

要回复问题请先登录注册