Lesson 4
Writing Table Data to CSV Files Using Python
Introduction and Context Setting

Welcome to the final lesson in our course focused on working with different files as data sources. In this lesson, you will learn how to write table data to a CSV file using Python's built-in csv module. Throughout this course, you have been introduced to various aspects of handling table data. We've covered parsing tables from text and CSV files and writing data to text files. Now, we'll bring our knowledge full circle by exploring how to export data to a CSV file, a common data format that is widely used for data exchange between different applications and platforms.

CSV (Comma-Separated Values) files allow for easy storage and sharing of structured data in a tabular format. Python's csv module simplifies working with CSV files, letting you store data efficiently. By the end of this lesson, you should be comfortable using the csv module to write data to CSV files.

Organizing Data for CSV Writing

Before we can write data to a CSV file, we need to prepare it. You should organize your data in a list of lists, where each sublist represents a row in the table. The first sublist typically acts as the header row, giving names to each column.

Here's an example:

Python
1data = [ 2 ['Name', 'Age', 'Occupation'], 3 ['John', '28', 'Engineer'], 4 ['Alice', '34', 'Doctor'], 5 ['Bob', '23', 'Artist'] 6]
Writing Data to a CSV File: Context Manager

First, you need to import the csv module. This module provides functionality for both reading from and writing to CSV files.

Python
1import csv

Next, specify the file path and open the file in write mode. Use the with statement to ensure the file is properly closed after completing the operations.

Python
1output_file_path = 'output.csv' 2with open(output_file_path, 'w', newline='') as csvfile:
  • output.csv is the name of the CSV file you will create or overwrite.
  • newline='' is used to prevent additional newline characters from being added, which can lead to blank lines in the output.
Writing Data to a CSV File: Final Step

You can now create a csv.writer object, which will handle the data being written into the file.

Python
1 csv_writer = csv.writer(csvfile)

This object (csv_writer) allows you to write to the file using a convenient interface provided by the module. Finally, use the writerows() method to write all your data to the file at once.

Python
1 csv_writer.writerows(data)

This method writes each sublist in your data array as a new row in the CSV file. The full code snippet:

Python
1output_file_path = 'output.csv' 2with open(output_file_path, 'w', newline='') as csvfile: 3 csv_writer = csv.writer(csvfile) 4 csv_writer.writerows(data)
Writing Data to a CSV File: Delimiter Parameter

When writing to a CSV file, you can customize the delimiter used to separate values in the file. The csv.writer object allows you to specify a different delimiter by using the delimiter parameter. By default, the delimiter is a comma (,), but you can set it to any character that suits your needs.

Here's how you can specify a custom delimiter:

Python
1csv_writer = csv.writer(csvfile, delimiter=';')

In the example above, a semicolon (;) is used as the delimiter instead of a comma. This change will affect how data is parsed by applications or scripts that consume the CSV file, so make sure the chosen delimiter is consistent with the expected format of the data consumer.

Compete Example

Let's see the complete example and its output.

Python
1import csv 2 3data = [ 4 ['Name', 'Age', 'Occupation'], 5 ['John', '28', 'Engineer'], 6 ['Alice', '34', 'Doctor'], 7 ['Bob', '23', 'Artist'] 8] 9 10output_file_path = 'output.csv' 11with open(output_file_path, 'w', newline='') as csvfile: 12 csv_writer = csv.writer(csvfile) 13 csv_writer.writerows(data) 14 15print(f"Data written to {output_file_path} as a CSV.")

Output:

Plain text
1Data written to output.csv as a CSV.

By running this code, you will have generated a CSV file named output.csv in your current directory, containing your table data.

Summary and Preparation for Practice

Congratulations on completing the course! You are now equipped with the skills to read, organize, and write table data across both text and CSV files using Python. In this lesson, you learned how to utilize the csv module to write structured data to a CSV file effectively, ensuring that your data is both accessible and shareable in a widely accepted format.

As you move forward, practice these skills with varied datasets to reinforce your understanding. Experiment with writing different types of structured data and observe how changes impact your CSV output. It's been a pleasure guiding you through this learning journey, and I'm confident these skills will significantly aid your data handling capabilities in real-world applications. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.