[英]Python: read multiple source txt files, copy by criteria into 1 output file
我的目标是读取一个文件夹(较小)中的多个txt源文件,然后将按条件选择的行复制到一个输出txt文件中。 我可以使用1个源文件执行此操作,但是当我尝试读取多个文件并执行相同操作时却没有输出(空)。
通过我的SO研究,我编写了以下代码(无输出):
import glob
# import re --- taken out as 'overkill'
path = 'C:/Doc/version 1/Input*.txt' # read source files in this folder with this name format
list_of_files=glob.glob(path)
criteria = ['AB', 'CD', 'EF'] # select lines that start with criteria
#list_of_files = glob.glob('./Input*.txt')
with open("P_out.txt", "a") as f_out:
for fileName in list_of_files:
data_list = open( fileName, "r" ).readlines()
for line in data_list:
for letter in criteria:
if line.startswith(letter):
f_out.write('{}\n'.format(line))
谢谢您的帮助。
@abe和@ppperry:非常感谢您之前的输入。
您的代码有问题:
files
和list_of_files
但仅使用后者。 data_list
,这会擦除先前读取的文件的内容。 data_list
,请使用变量fileName
而不是data_list
! 可以简化的地方:
re
模块只是为了确定一个字符串是否以另一个字符串开头,所以使用re
模块是多余的。 您可以使用line.startswith(letter)
。 错误:
这是固定的代码,带有注释:
import glob
import re
#path = 'C:\Doc\version 1\Output*.txt' # read all source files with this name format
#files=glob.glob(path)
criteria = ['AB', 'CD', 'EF'] # select lines that start with criteria
list_of_files = glob.glob('./Output*.txt')
with open("P_out.txt", "a") as f_out: #use "a" so you can keep the data from the last Output.txt
for fileName in list_of_files:
data_list = open( fileName, "r" ).readlines()
#indenting the below will allow you to search through all files.
for line in data_list: #Search data_list, not fileName
for letter in criteria:
if re.search(letter,line):
f_out.writelines('{}\n'.format(line))
#I recommend the \n so that the text does not get concatenated when moving from file to file.
#Really? I promise with will not lie to you.
#f_out.close() # 'with' construction should close files, yet I make sure they close
对于那些反对的人,为什么不添加评论以证明您的判断正确呢? OP要求的所有条件都已满足。 如果您认为可以进一步改善答案,请提出修改建议。 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.