DEV Community

Cover image for Working with CSV Files in Python
Paulo GP
Paulo GP

Posted on • Updated on

Working with CSV Files in Python

Introduction

Journey into the realm of data management as we explore the intricacies of handling CSV (Comma Separated Values) files with Python. In this chapter, we'll delve into the mechanics of CSV file manipulation, from understanding its structure to executing operations like reading and writing data. Python equips us with robust tools to navigate this domain with ease and efficiency.

Topics

  • Deciphering CSV Structure
  • Reading Data from CSV Files
  • Writing Data to CSV Files

Deciphering CSV Structure

CSV files encapsulate tabular data, featuring rows as records and columns separated by a designated delimiter, usually a comma. This format facilitates easy parsing and manipulation of structured data. Let's examine a sample CSV file to grasp its layout:

CSV File sample_data.csv:

"ID","Name","Age"
"1","Alice",25
"2","Bob",30
"3","Charlie",28
Enter fullscreen mode Exit fullscreen mode

Reading Data from CSV Files

Python's csv module provides robust functionalities for reading data from CSV files. Using its DictReader class, we can effortlessly parse CSV records into dictionaries, facilitating convenient data access:

import csv

# Open CSV file for reading
with open(file="sample_data.csv", mode="r") as file:
    reader = csv.DictReader(f=file)
    for row in reader:
        print("Data Record:")
        print(f"ID: {row['ID']}")
        print(f"Name: {row['Name']}")
        print(f"Age: {row['Age']}")
        print("-" * 20)
Enter fullscreen mode Exit fullscreen mode

Output:

Data Record:
ID: 1
Name: Alice
Age: 25
--------------------
Data Record:
ID: 2
Name: Bob
Age: 30
--------------------
Data Record:
ID: 3
Name: Charlie
Age: 28
--------------------
Enter fullscreen mode Exit fullscreen mode

Writing Data to CSV Files

Similarly, Python's csv module empowers us to write data to CSV files effortlessly. By utilizing its DictWriter class, we can craft CSV records from dictionaries and inscribe them onto the canvas of our chosen CSV file:

import csv

# Data to be written to CSV file
new_records = [
    {"ID": "4", "Name": "David", "Age": "35"},
    {"ID": "5", "Name": "Eve", "Age": "32"}
]

# Open CSV file for writing
with open(file="new_data.csv", mode="w", newline="") as file:
    writer = csv.DictWriter(f=file, fieldnames=["ID", "Name", "Age"])
    writer.writeheader()
    for record in new_records:
        writer.writerow(record)
Enter fullscreen mode Exit fullscreen mode

Conclusion

Mastering the manipulation of CSV files with Python opens doors to efficient data management practices. By understanding the structure of CSV files and leveraging the capabilities of Python's csv module, we gain the ability to seamlessly read, write, and manipulate tabular data. Armed with these skills, we embark on a journey of data exploration and manipulation, forging pathways to unlock the potential of our datasets.

Top comments (4)

Collapse
 
sc0v0ne profile image
sc0v0ne

Better than using pandas to read, ahahahha !!!

Collapse
 
manhdt profile image
thitkhotau

How to you think about using configparser or json to manage server configuration data? (I think it is convenient than using .csv.)

Collapse
 
tlayach profile image
Paulo GP

The examples in the post are for educational purposes only. I have another post that talks about the JSON format. I will try to rewrite the post using, for example, books. Thank you.

Collapse
 
manhdt profile image
thitkhotau

I saw some small projects, using .csv to create test data. Is it useful? I really don't want using csv. It's difficult to read and update raw data.