I encounter this question when I want to parse a file with large size using pyparsing. I have already created the pyparsing grammar for the whole file. But I am not sure how to feed the string to the parser line by line by reading this big file. Currently I am using the the method like:
pyparsingGrammer = some pyparsing grammar I created
PyparsingGrammar.parseString(open(filename).read())
Except the memory usage for the big read(), another motivation for me to go for line feeding is to extend my parser to a realtime case where info is feeded to the parser one line followed by another.
You could do :
using the keyword
withautomatically closes the file once you are done, and gives you a handle to work with.is a standard way of going over iterables (stuff which can be iterated, e.g:
list, tuple, dictionaryin Python.I forgot to mention, but I guess you figured it:
when you open a file in Python with
with open(filename) as fyou are getting alistwhere each line in the list is an item. That is why you are able to treatfas an iterator.