Write Lists as CSV Records (Solution)
00:00
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.
00:16
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 numbers.csv
.
00:34
As usual, I’ll use the with
statement to open the file represented by that path, and I’ll set the mode to writing, using UTF-8 as the character encoding.
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.
01:07
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.
01:20
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.
01:37
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.
02:10
The 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.
02:24
Here I pass the numbers
variable as an argument because that’s what we want to be written to the file.
02:31
Let’s save the solution as exercise_02_01
and run it.
02:40
Nothing’s happened in the console, but we can open the file that should have been created by our little script. The name of the file was numbers.csv
. Perfect.
02:51 We just created a CSV file, and it seems that all data was written correctly.
02:57 Next, you’ll practice reading such data from a file, which is equally important.
Become a Member to join the conversation.