Efficiently extract lines containing a string in Python

独自空忆成欢 提交于 2021-01-29 18:08:18

问题


Sometimes I need to get only lines containing a certain string from a text file (e.g., while parsing a logfile). I usually do it this way:

with open(TEXTFILENAME,'r') as f:
  contents = f.readlines()

targets = [s for s in contents if FINDSTRING in s]

However, I saw there's a possible two-liner:

with open(TEXTFILENAME,'r') as f:
  targets = [s for s in f.readlines() if FINDSTRING in s]

I wonder if the second method is more efficient, whether the readlines() function in this case act as an iterator of sorts.


回答1:


Avoid the call to readlines, which generates a list of all the lines. This should therefore be faster

with open(TEXTFILENAME,'r') as f:
    targets = [line for line in f if FINDSTRING in line]


来源:https://stackoverflow.com/questions/26112683/efficiently-extract-lines-containing-a-string-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!