- [Instructor] Being able to read CSV files
is only half the equation.
We need to be able to write CSV data as well.
The CSV module provides a set of classes
and functions for doing exactly that.
So in this example, we're going to see
how to write data that is in an array format,
and we'll see how to write dictionary data
in a separate video.
So for this example, let's open up write_csv_array.py.
And for this example, you can see
that I've already got some code
that defines an array of rows of data.
The first row is the header information,
and the rest of the rows contain lists
of different food types and prices.
It's essentially a subset of the inventory file
that we've been working with in the chapter.
So let's write a function
that will write the data to a CSV file.
So let's declare the function,
and we'll call it write_array_to_csv.
And that will take in the data to write
along with a filename.
Then all we need to do
is open the file that we want to write to.
So I'll use my with open statement,
and I'll pass in the filename.
And this time I'm going to use write mode.
And I'm going to specify the new line
is equal to an empty space,
which means write out the line endings
according to what your operating system prefers.
And I'll open that as csvfile.
And then we just need to write the data.
So I'm going to make a variable called writer,
and I'll create a csv.writer object
with the CSV file I just opened.
And using that writer, I'm going to call writerows
to write multiple rows of data.
And that's pretty much all there is to it.
You can see it's a little easier than reading the data.
So all we need to do now is call that function.
So let's call write_array_to_csv,
and we'll pass in my data array,
which is defined right here.
And we'll give it a name.
We'll call it output.csv.
All right, so let's save
and let's try running this.
All right, and when I run this,
you can see that over here in the sidebar
a little output.csv file has shown up.
So let's click on it.
And sure enough, it contains the data from the array.