How to Store CSV File in Python: A Complete Guide

Python is a popular programming language that supports several file formats, including CSV (Comma Separated Values). CSV files are used by many data analysts and programmers to store tabular data in a human-readable format. In this blog post, you will learn how to store CSV files in Python.

What is a CSV file?

A CSV file is a simple text-based format used for storing tabular data. Each line of the file represents one row of the table, with each column separated by commas. For example:

“`
Name, Age, Gender
John Doe, 25,Male
Jane Smith, 30,Female
Bob Johnson, 45,Male
“`

Creating a CSV File

Before we can start storing our data into a csv file using python we need to create one first. Here’s an example on how you could do it.

“`python
import csv

with open(‘example.csv’, ‘w’, newline=”) as csvfile:
fieldnames = [‘Name’, ‘Age’, ‘Gender’] # headers for your columns within your table

writer = csv.DictWriter(csvfile)

writer.writerow({‘Name’: ‘John Doe’, ‘Age’: 25,’Gender’: ‘Male’})

“`

In this code snippet above `csv.DictWriter()` class constructs an object which operates like regular writer but maps dictionaries onto output rows.The `writerow()` function writes the values passed as argument into the current row in the opened csv file.

Now let’s dive right into understanding on how we could write more than one row within our newly created csv.

Writing Multiple Rows To A Csv File

“`python

import csv

with open(‘example1.csv’, mode=’w’) as employee_file:
employee_writer=csv.writer(employee_file, delimiter=’,’, quotechar='”‘, quoting=csv.QUOTE_MINIMAL)
employee_writer.writerow([‘Name’,’Age’,’Gender’])
employee_writer.writerow([‘John Doe’, 25,’Male’])
employee_writer.writerow([‘Jane Smith’, 30,’Female’])

“`

The `csv.writer` function writes a row of data into the csv file. In this code snippet above each row is created via writersow() method and the column values are separated by commas.

Reading Data From A Csv File

“`python

import csv

with open(‘example.csv’) as csvfile:
readCSV = csv.reader(csvfile, delimiter=’,’)
for row in readCSV:
print(row)

“`

The `csv.reader()` function reads each line of your CSV file and returns a list of values. We then loop over these rows using a for loop to print that on our console log.

Conclusion

Storing CSV files in Python is an essential skill for any programmer or data analyst working with tabular data sets. With the help of built-in libraries like ‘CSV’ you can easily create, write to, and read from CSV files in Python with just a few lines of code. If you’re looking to further your knowledge – experimenting around different functionalities within these libraries would be good start!

Share this post: