From the course: Advanced Hands-On Python: Working with Excel and Spreadsheet Data

Unlock the full course today

Join today to access over 24,600 courses taught by industry experts.

Writing a CSV file

Writing a CSV file

- [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…

Contents