Write Lists as CSV Records (Solution)
The exercise instructions provide a code snippet that we can cut and paste into our solution. It defines a variable named
numbers, which is assigned a list of elements, and each element is a nested list of integers.
Now I need to open a file for writing where this data will be saved. So I’ll import the
pathlib.Path object, and I can specify the path to the CSV file in my home directory, which should be named
00:46 Now, unlike before when we were working with generic text files, we now want to write a more specific kind of text file—that is, one using the CSV format. While writing and reading such files by hand may seem straightforward, there are actually surprisingly many edge cases and CSV dialects, which is why it’s almost never a good idea.
Fortunately, Python comes with the
csv module in the standard library, which can handle the quirks of the CSV format. So that’s what I’ll use. I need to add another
import statement at the top of the file.
In this case, I’m importing the entire module instead of a specific symbol from it, so I’ll have to prefix whatever object I want to use with the module name, and now I can create a new CSV
writer object to wrap the file with.
Before moving further, there’s one more thing I should address. Whenever using the
csv module, it’s considered best practice to disable Python’s universal newline translation mechanism by setting the file’s
newline parameter to an empty string.
01:53 This ensures that newlines that might appear as values in the CSV file are handled correctly in a portable way across different operating systems. This might not be necessary in this particular case, but it helps to cultivate good programming habits.
writer object provides convenient methods such as
.writerows(), which takes a Python list as an argument and converts its elements into CSV-formatted rows before writing them to the provided file.
Become a Member to join the conversation.