Friday, November 22, 2013

The correct way to read a text file in Python

When you search for examples of reading a file on the web, most examples you see show:

with open('file') as f:
  text = f.read()

But it's quite hard to find examples of the "correct" or "proper" way to read text files in Python. Of course correct/proper is a matter of opinion and depends on what you're trying to accomplish. In many cases you really want to slurp the full file into memory as above, but in my case I more often need to process one line at a time (perhaps in conjunction with a generator), in which case this is what I need:

with open('file') as f:
  for line in f:
    yield line

Not to mention that you'd deal with binary files in a different way as well...
Post a Comment