Representative Line: What a Character

This post was originally published on this site

The Daily WTF

Python’s “batteries included” approach means that a lot of common tasks have high-level convenience functions for them. For example, if you want to read all the lines from a file into an array (list, in Python), you could do something like:

with open(filename) as f: lines = f.readlines()

Easy peasy. Of course, because it’s so easy, there are other options.

For example, you can just convert the file directly to a list: lines = list(f). Or you can iterate across the file directly, e.g.:

with open(filename) as f: for line in f: # do stuff

Of course, that’s fine for plain old text files. But we frequently use text files which are structured in some fashion, like a CSV file. No worries, though, as Python has a csv library built in, which makes it easy to handle these files too; especially useful because “writing a CSV parser yourself”

To read the full article click on the 'post' link at the top.