Efficiently extract lines containing a string in Python
问题 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