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 =

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...

1 comment:

Unknown said...

You have done a great job. I will definitely dig it and personally recommend to my friends. I am confident they will be benefited from this site.friv jogos online
jogos online 2019
friv jogos 4 school online