繁体   English   中英

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

[英]How to search specific lines in a file and write them to another file, using function in 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'
fi = infile.readlines()

这使fi成为文件infile中的行列表。 因此,当您稍后调用fi.close() ,您尝试关闭列表,这当然是行不通的。

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

infile.close()

通常,以某种方式更改变量名是一个好主意,这样可以清楚地知道它们包含的内容。 infile是您从中读取的文件对象,因此可以。 outfile是要写入的文件的文件名 ,因此应将其命名为outFileName或其他名称。 fiinfile中的行的列表,因此您应该将其inFileLines

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

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

最后,您的代码还有另一个问题: re.findall('search1' , str(line))这将re.findall('search1' , str(line))搜索字符串'search1' 它不会尊重正在传递给函数和被存储在所述值search1 (和search2 )变量。 因此,您需要在其中删除引号: re.findall(search1, line) (您也不需要将行转换为字符串)。

另外,如果仅评估re.findall()的真值,则不是最好的方法。 相反,使用re.search仅返回第一个结果(因此对于很长的行 ,如果您已经找到结果,则不会继续搜索)。 如果search1以及search2将不包含实际正则表达式,但只是字符串要在网上找到,那么你也应该只使用in运营商:

if search1 in line:
    write1 = True

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

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

如果您想多次使用一个文件,则必须从头开始才能再次读取文件。 在您的情况下,由于您正在使用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, …)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM