What a Character – 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:
		

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” is one of those tasks that sounds easy until you hit the first edge case, and then you realize you’ve made a terrible mistake.

Now, it’s important to note that CSV usually is expressed as a “comma separated values” file, but the initialism is actually “character separated values”. And, as Sally‘s co-worker realized, newlines are characters, and thus every text file is technically a CSV file.

foo = list(csv.reader(someFile, delimiter="\n"))

Source link

Stay in the Loop

Get the daily email from CryptoNews that makes reading the news actually enjoyable. Join our mailing list to stay in the loop to stay informed, for free.

Latest stories

You might also like...