@Maxime's comment just beats it all:
def read_file(file_path):
with open(file_path, 'rb') as f:
yield from f
for line in read_file('filename'):
# do sth
This uses Python's yield from
, explained at In practice, what are the main uses for the new "yield from" syntax in Python 3.3?.
And to validate your concerns, here is the Zen of Python (import this
)
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
It really gets ugly at four (?) and more levels of indentation. In that case, you might be well-advised to clean this up, and move the whole file-handling code to a function, like so:
with open('filename', 'rb') as f:
parse_file(f)
def parse_file(f):
for line in f:
# do stuff
It gets really deep when you start adding classes etc to the mix ....
Apart from that: do you have a nice editor, that eases the indentation etc? While not for everyone, emacs is actually quite good with Python