Reading and Writing CSV Files using Python

CSV (Comma Separated Values) files are the most commonly used file format for importing and exporting big datasets. The reason why a CSV file is preferred over an Excel file is that a CSV file consumes less memory as compared to an Excel file. So while learning data science, you must know how to read and write CSV files. If you want to learn how to read and write CSV files, this article is for you. In this article, I will take you through a tutorial on reading and writing CSV files using Python.

Reading and Writing CSV Files using Python

You can read and write a CSV file without using any Python module or a library. But as we use the pandas library to work with data, this article will teach you how to read and write a CSV file using the pandas library in Python.

So let’s start by writing a CSV file. Here I will first create a sample data using a Python dictionary about the name and age of students, and then I will store that Python dictionary into a CSV file:

# writing a csv file
import csv
import pandas as pd
data = {"Name": ["Aman", "Diksha", "Akanksha", "Sajid", "Akshit"], 
        "Age": [23, 21, 25, 23, 22]}
data = pd.DataFrame(data)
data.to_csv("age_data.csv", index=False)
print(data.head())
       Name  Age
0      Aman   23
1    Diksha   21
2  Akanksha   25
3     Sajid   23
4    Akshit   22

So this is how you can write a CSV file using Python. Now below is how you can read this CSV file using Python:

# reading a csv file
import pandas as pd
data = pd.read_csv("age_data.csv")
print(data.head())
       Name  Age
0      Aman   23
1    Diksha   21
2  Akanksha   25
3     Sajid   23
4    Akshit   22

So this is how easy it is to read and write a CSV file using the pandas library in Python.

Summary

So this is how you can read and write CSV files using the Python programming language. CSV files are the most commonly used file format for importing and exporting datasets. So while learning data science, you must know how to read and write CSV files. I hope you liked this article on a tutorial on reading and writing CSV files using Python. Feel free to ask valuable questions in the comments section below.

Default image
Aman Kharwal

Coder with the ♥️ of a Writer || Data Scientist | Solopreneur | Founder

Articles: 1211

Leave a Reply