如何使用Python中的函数搜索文件中的特定行并将它们写入另一个文件

2024-10-04 01:26:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是建立一个日志解析器,它将复制我想要的关键字之间的选定行,并写入一个文件。因为我必须在单个文件中的多个关键字之间进行搜索,所以我想到编写一个函数并在脚本中多次使用它。你知道吗

但是,我无法通过以下脚本实现这一点,并且出现了一个错误:

import re

def myfunc (infile ,outfile, search1 , search2):

    fi =  infile.readlines()
    fo =  open(outfile, 'w')

    write1 = False
    for line in fi:
     if re.findall('search1' , str(line)):
        write1 = True
     elif re.findall('search2', str(line)):
        write1 = False
     elif write1:
        fo.write(line)

    fo.close()
    fi.close()

    return;

text_file = open(input("name of inputfile : "))
resultfile =  input("name of outputfile : ")

search1 = "teen"
search2 = "eight"
myfunc (text_file , resultfile , search1 , search2)

我收到以下错误:

Traceback (most recent call last):
  File "C:/Users/zoro/PycharmProjects/text-parsing/write selected test 2 sets.py", line 38, in <module>
    myfunc (text_file , resultfile , search1 , search2)
  File "C:/Users/zoro/PycharmProjects/text-parsing/write selected test 2 sets.py", line 28, in myfunc
    fi.close()
AttributeError: 'list' object has no attribute 'close'

Tags: textinrecloseline关键字myfuncfi
1条回答
网友
1楼 · 发布于 2024-10-04 01:26:05
fi = infile.readlines()

这使得fi成为文件infile中的行列表。因此,当您稍后调用fi.close()时,您试图关闭一个列表,这当然不起作用。你知道吗

相反,您需要关闭文件,即infile

infile.close()

一般来说,改变变量名是一个好主意,这样就可以清楚地知道它们包含什么。infile是一个文件对象,可以从中读取。outfile是要写入的文件的文件名,因此应该将其命名为outFileName或其他名称。fiinfile中的行列表,因此您应该称之为maybeinFileLines。你知道吗

您还应该避免手动关闭文件对象;而是使用with语句来确保它们自动关闭:

with open(outfile, 'w') as fo:
    fo.write('stuff')
    # no need to manually close it

最后,代码还有另一个问题:re.findall('search1' , str(line))这将搜索行中的字符串'search1';它将不考虑传递给函数并存储在search1(和search2)变量中的值。因此您需要删除那里的引号:re.findall(search1, line)(您也不需要将行转换为字符串)。你知道吗

另外,如果只计算它的真值,那么使用re.findall()并不是最好的方法。相反,使用re.search,它只返回第一个结果(因此对于真正的长行,如果已经找到结果,就不会继续搜索)。如果search1search2不包含实际的正则表达式,而只包含希望在行中找到的字符串,那么还应该使用in运算符:

if search1 in line:
    write1 = True

最后一点注意:文件句柄应该始终从打开它们的同一级别关闭。因此,如果在函数中打开一个文件句柄,那么函数也应该关闭它。如果在函数外部打开文件,则函数不应将其关闭。打开程序负责关闭文件,对于其他实例,关闭文件可能会导致错误行为,因此您不应该这样做(除非有明确的文档记录,例如函数doSomethingAndClose可能会关闭文件)。你知道吗

使用with语句通常可以避免这种情况,因为您从不手动调用file.close(),而且with语句已经确保文件正确关闭。你知道吗

如果您想多次使用一个文件,那么您必须seek to the beginning才能再次读取它。在您的例子中,由于您使用infile.readlines()将整个文件读入内存,因此最好只从文件中读取一次行,然后将其重新用于多个函数调用:

text_file = input("name of inputfile : ")
with open(text_file) as infile:
    fi = infile.readlines() # read the lines *once*

    myfunc(fi, …)
    myfunc(fi, …)
    myfunc(fi, …)

相关问题 更多 >