python
  1. python-write-csv-file

Python Write CSV File

CSV (Comma Separated Values) is a popular format for storing and exchanging data. Python provides the csv module to work with CSV files. In this tutorial, we will learn how to write CSV files in Python using the csv module.

Syntax

import csv

with open('filename.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['column1', 'column2'])
    writer.writerows([['row1data1', 'row1data2'], ['row2data1', 'row2data2']])

Example

Suppose we have a list of dictionaries representing student data with fields like name, age, and grade. We want to write this data to a CSV file. Here is how we can do it in Python:

import csv

students = [
    {'name': 'John', 'age': 25, 'grade': 'A'},
    {'name': 'Sara', 'age': 22, 'grade': 'B'},
    {'name': 'Harry', 'age': 28, 'grade': 'A'},
    {'name': 'Frank', 'age': 31, 'grade': 'C'}
]

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    
    # Write header row
    writer.writerow(['Name', 'Age', 'Grade'])
    
    # Write each student's data
    for student in students:
        writer.writerow([student['name'], student['age'], student['grade']])

Output

The above code will create a CSV file named students.csv with the following contents:

Name,Age,Grade
John,25,A
Sara,22,B
Harry,28,A
Frank,31,C

Explanation

Here's how the above code works:

  • First, we import the csv module.
  • Next, we define a list of dictionaries representing student data.
  • We open a new CSV file named students.csv in write mode with the csv.writer() method.
  • We then write the header row to the CSV file using the writerow() method.
  • Finally, we loop through the student data and write each student's data to the CSV file using the writerow() method.

Use

You can use Python to write CSV files for storing and exchanging data in a format that is widely supported by other applications like Microsoft Excel, Google Sheets, and many others.

Important Points

  • When opening a CSV file for writing, specify the newline='' parameter to ensure that newlines are handled properly.
  • Use the csv.writer() method to create a writer object to write data to the CSV file.
  • Use the writerow() method to write a single row of data to the CSV file.
  • Use the writerows() method to write multiple rows of data to the CSV file.

Summary

In this tutorial, we learned how to write CSV files in Python using the csv module. We saw how to write header rows, write rows of data, and handle newlines. We also saw a practical example of writing student data to a CSV file.

Published on: