reading specific lines from a file
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 fi开发者_高级运维rst place?
To do it without loading the whole file into memory, just iterate over the file:
match_txt = "lhcb"
for file_name in os.listdir('.'):
with open(file_name) as f:
for line in f:
if line.startswith(match_txt):
#< do stuff here >
If you want to check for match_txt
anywhere in the line, you can use
if match_txt in line:
Your example code is equivalent to checking if the line starts with match_txt
though.
If you're using a very old version of Python that doesn't have the with
statement, you'll have to close the file manually:
match_txt = "lhcb"
for file_name in os.listdir('.'):
f = open(file_name)
for line in f:
if line.startswith(match_txt):
#< do stuff here >
f.close()
You should look into the str.startswith() function.
if line.startswith("text"):
http://docs.python.org/library/stdtypes.html#str.startswith
精彩评论