You are currently viewing Python: How to Write CSV Files

Python: How to Write CSV Files

CSV (Comma Separated Values) files are widely used for storing data in a structured, tabular format. Python’s built-in csv module provides a user-friendly approach for reading and writing data in this format. The code example is an excellent starting point for learners who are interested in learning how to create CSV files in Python for their specific data storage and analysis requirements:

import csv

filename = 'demo.csv'

data = [
    ['Edward', 24, 'Male', 'Single', 'Python'],
    ['Edward Jr.', 10, 'Male', 'Single', 'Dart'],
    ['Samantha', 22, 'Female', 'Single', 'JavaScript'],
    ['Cherish', 15, 'Female', 'Single', 'C++'],
    ['Lucia', 15, 'Female', 'Single', 'Swift'],
]

if __name__ == '__main__':

    with open(filename, 'w') as csvfile:

        writer = csv.writer(csvfile, dialect='excel')

        headers = ['name', 'age', 'gender', 'marital status', 'language']

        writer.writerow(headers)

        for row in data:
            writer.writerow(row)

        print(f"Successfully created csv file '{filename}'.")

It is crucial to note that the code solely deals with the process of creating and writing to a CSV file. For those interested in understanding how to read data from CSV files using Python, please refer to my other article on this topic titled Working with CSV Files in Python: Reading.

I sincerely hope that you find this code helpful. If you wish to learn more about Python, please subscribe to our newsletter today and continue your Python learning journey with us!

Leave a Reply