What a Character – The Daily WTF

Date:

Share:

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

Subscribe to our magazine

━ more like this

An AI-first approach: How RB2B created a lean, scalable support system

As RB2B scaled, its support team needed a way to handle growing demand without adding headcount. Head of Technical Operations Robb Clarke turned to AI...

20 Funny Cat Photos Caught At The Purrfect Meowment

As cat owners, we know that for the most part, cats don't really do much. They nap in sunbeams, demand food with dramatic meows,...

Amazon Big Spring Sale Best Beauty Deals

Lemme Glow Collagen Gummies ($22, originally $30) Kourtney Kardashian Barker's Lemme Glow gummies are packed with hair, skin, and nail heroes. There are collagen...

I Think Paramount+ Is Making a Huge Mistake With NCIS: Tony & Ziva

NCIS lost a big part of what made it so great when Tony (Michael Weatherly) and...