Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

How to Read and Write CSV Files in Python: A Comprehensive Guide

What Is a CSV File?

A CSV (Comma‑Separated Values) file stores tabular data in plain text. Each line represents a row, and individual fields are separated by a comma, semicolon, or another delimiter. CSV files are lightweight, widely supported by spreadsheets, databases, and data‑analysis tools, making them a preferred format for data interchange.

CSV Sample File

Below is a typical CSV representation of a small programming‑language database. The first row contains column headers, followed by rows of data.

Table Data

Programming language Designed by Appeared Extension
Python Guido van Rossum 1991 .py
Java James Gosling 1995 .java
C++ Bjarne Stroustrup 1983 .cpp

CSV Data

Programming language,Designed by,Appeared,Extension
Python,Guido van Rossum,1991,.py
Java,James Gosling,1995,.java
C++,Bjarne Stroustrup,1983,.cpp

Download CSV Data

Python’s Built‑In csv Module

The csv module provides low‑level tools for reading and writing CSV files. It handles quoting, delimiters, and line terminators automatically, reducing the need for manual string manipulation.

Key Functions

Reading a CSV File

Below is a minimal, production‑ready example that reads a CSV file and prints each row as a Python list.

import csv

with open('data.csv', mode='r', newline='', encoding='utf-8') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

The output will be:

["Programming language", "Designed by", "Appeared", "Extension"]
["Python", "Guido van Rossum", "1991", ".py"]
["Java", "James Gosling", "1995", ".java"]
["C++", "Bjarne Stroustrup", "1983", ".cpp"]

Reading CSV into a Dictionary

Using csv.DictReader automatically maps the header row to dictionary keys, simplifying data handling.

import csv

with open('data.csv', mode='r', newline='', encoding='utf-8') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)

Resulting dictionaries:

{"Programming language": "Python", "Designed by": "Guido van Rossum", "Appeared": "1991", "Extension": ".py"}
{"Programming language": "Java", "Designed by": "James Gosling", "Appeared": "1995", "Extension": ".java"}
{"Programming language": "C++", "Designed by": "Bjarne Stroustrup", "Appeared": "1983", "Extension": ".cpp"}

Writing a CSV File

The csv.writer and csv.DictWriter classes let you write data efficiently.

import csv

rows = [
    ["Programming language", "Designed by", "Appeared", "Extension"],
    ["Python", "Guido van Rossum", "1991", ".py"],
    ["Java", "James Gosling", "1995", ".java"],
    ["C++", "Bjarne Stroustrup", "1983", ".cpp"],
]

with open('writeData.csv', mode='w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer.writerows(rows)

The generated writeData.csv will match the original sample.

Using Pandas for CSV Operations

Pandas simplifies CSV handling by loading data into a DataFrame, enabling powerful data manipulation with minimal code. Install with pip install pandas if not already available.

Reading with Pandas

import pandas as pd

df = pd.read_csv('data.csv')
print(df)

Output:

  Programming language        Designed by  Appeared Extension
0               Python  Guido van Rossum      1991      .py
1                Java     James Gosling      1995     .java
2                C++   Bjarne Stroustrup      1983     .cpp

Writing with Pandas

import pandas as pd

data = {
    'Programming language': ['Python', 'Java', 'C++'],
    'Designed by': ['Guido van Rossum', 'James Gosling', 'Bjarne Stroustrup'],
    'Appeared': ['1991', '1995', '1983'],
    'Extension': ['.py', '.java', '.cpp'],
}

df = pd.DataFrame(data)
df.to_csv('pandaresult.csv', index=False)
print(df)

Resulting CSV is identical to the original, but the DataFrame offers advanced analytics capabilities.

Conclusion

Python’s csv module and Pandas provide robust, easy‑to‑use tools for reading, writing, and manipulating CSV files. Mastering these libraries unlocks efficient data workflows across web services, ETL pipelines, and scientific research. Start experimenting today and integrate CSV handling into your projects with confidence.

Python

  1. Python Namespaces & Variable Scope: Understanding Names, Bindings, and Scopes
  2. Python File I/O: Mastering File Operations, Reading, Writing, and Management
  3. Retrieve Current Date and Time in Python: A Practical Guide
  4. Reading Files in Java with BufferedReader – A Practical Guide with Examples
  5. Master Python File Handling: Create, Read, Write, and Open Text Files with Ease
  6. Checking File and Directory Existence in Python – A Practical Guide
  7. How to Rename Files and Directories in Python with os.rename() – Step-by-Step Guide
  8. Python JSON: Encoding, Decoding, and File Handling – A Practical Guide
  9. Master XML Parsing in Python: A Practical Guide Using Minidom and ElementTree
  10. Use gRPC in Python to Read and Write Process Data on an AXC F 3152