Python 如何从一个文本文件中创建包含多行但不是所有行的列表?
我是新来的,我想问你一件事。我刚开始用Python编程,我的目标是读取和分析日志文件 日志文件有成百上千行,每个文件都包含一个密钥号。现在我想创建一个子日志文件,它只包含带有特定键号的行 首先,我创建了搜索字符串和子日志文件:Python 如何从一个文本文件中创建包含多行但不是所有行的列表?,python,python-2.7,Python,Python 2.7,我是新来的,我想问你一件事。我刚开始用Python编程,我的目标是读取和分析日志文件 日志文件有成百上千行,每个文件都包含一个密钥号。现在我想创建一个子日志文件,它只包含带有特定键号的行 首先,我创建了搜索字符串和子日志文件: search_string1 = str(160000004) file_out1 = open("outlier.txt","w") search_string2 = str(160030003) file_out2 = open("valid.txt","w")
search_string1 = str(160000004)
file_out1 = open("outlier.txt","w")
search_string2 = str(160030003)
file_out2 = open("valid.txt","w")
search_string3 = str(150090000)
file_out3 = open("triang.txt","w")
with open ("log.txt","r") as input_file:
for line_number, line in enumerate(input_file):
if search_string1 in line:
file_out1.write(line)
if search_string2 in line:
file_out2.write(line)
if search_string3 in line:
file_out3.write(line)
现在,我逐行分析主日志文件,并将包含搜索字符串的行写入子日志文件:
search_string1 = str(160000004)
file_out1 = open("outlier.txt","w")
search_string2 = str(160030003)
file_out2 = open("valid.txt","w")
search_string3 = str(150090000)
file_out3 = open("triang.txt","w")
with open ("log.txt","r") as input_file:
for line_number, line in enumerate(input_file):
if search_string1 in line:
file_out1.write(line)
if search_string2 in line:
file_out2.write(line)
if search_string3 in line:
file_out3.write(line)
我现在遇到的问题是,文件似乎写得不正确。如果我打印结果
,例如,我得到289行,其中包含我的搜索字符串。
但在我的子日志文件中,只写入了253行,最后一行甚至没有完成:
160000004 0.00% < fold | 4.31% outlier
160000004 0.00% < fold | 0.00% outlier
160
160000004 0.00%
谁能告诉我我的错在哪里吗?提前感谢!!=) 默认情况下,出于性能原因,会缓存文件IO。也就是说,写入文件并不意味着数据被立即写入文件,它可能仍在数据缓冲区中,等待写入。为了确保所有内容都已写入,您需要对文件调用flush(),这将导致所有等待的缓冲区都写入磁盘。另外,如果您已经处理完文件(至少现在是这样),关闭它们是一个好主意。关闭还会导致自动刷新所有缓冲区。因此,基本上您应该在for循环之后添加以下代码:
file_out1.close()
file_out2.close()
file_out3.close()
完成循环后是否关闭输出文件?使用
with
打开输入文件;为什么不使用它打开输出文件?然后文件将在with块的末尾关闭。