reading specific lines from a file
Posted
by
MacUsers
on Stack Overflow
See other posts from Stack Overflow
or by MacUsers
Published on 2011-02-13T23:21:52Z
Indexed on
2011/02/13
23:25 UTC
Read the original article
Hit count: 185
python
What's the best way of reading only the specific lines (based on matching text) from a file? This is what I'm doing now:
match_txt = "lhcb"
for inFile in os.listdir('.'):
readFile = open(inFile, 'r')
lines = readFile.readlines()
readFile.close()
for line in lines:
if line.find(match_txt)==0:
#< do stuff here >
i.e. I'm reading the lines, only with "lhcb" in it, from all the files in the present directory one by one. Is it the best way of doing that? Can it be done without loading the whole file in the memory in the first place?
© Stack Overflow or respective owner