Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Python CSV

Learn how to read and write tabular CSV data with Python’s csv module.

Levels: Intermediate ~25 min read

Intermediate

CSV (Comma-Separated Values) is a common text format for tabular data. Python’s csv module reads and writes CSV rows while handling details such as delimiters and quoting. File I/O still provides the file object; csv provides the tabular-data interpretation.

Read CSV rows

Use csv.reader() with an iterable of text lines. When the source is a file object, open the file with newline="" so the csv module can handle newline characters correctly. Each row is returned as a list of strings.

python
import csv
from io import StringIO

data = "name,score\nAda,10\nGrace,20\n"

for row in csv.reader(StringIO(data)):
    print(row)

Write CSV rows

Use csv.writer() to turn sequences into CSV rows. A writer writes text to an object with a write() method. When the destination is a file object, open it with newline="".

python
import csv
from io import StringIO

output = StringIO(newline="")
writer = csv.writer(output)
writer.writerow(["name", "score"])
writer.writerow(["Ada", 10])

print(output.getvalue())

Read and write dictionary rows

DictReader maps each row to a dictionary using the column names as keys. DictWriter writes dictionaries using a fieldnames sequence that defines the columns and their order.

python
import csv
from io import StringIO

data = "name,score\nAda,10\nGrace,20\n"

for row in csv.DictReader(StringIO(data)):
    print(row["name"], row["score"])

Use CSV files with File I/O

The csv module works with the file objects you learned about in File I/O. For a real CSV file, use open() with newline="". If the file is text, you can also specify an encoding such as UTF-8.

python
import csv
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "people.csv"

    with open(path, "w", encoding="utf-8", newline="") as file:
        writer = csv.writer(file)
        writer.writerow(["name", "score"])
        writer.writerow(["Ada", 10])

    with open(path, encoding="utf-8", newline="") as file:
        for row in csv.reader(file):
            print(row)

CSV values are text by default

csv.reader() and csv.DictReader() return field values as strings by default. The csv module does not infer integers, floats, dates, or other application-specific types for ordinary reads, so convert values explicitly when your program needs another type.

python
import csv
from io import StringIO

for row in csv.DictReader(StringIO("name,score\nAda,10\n")):
    score = int(row["score"])
    print(type(row["score"]).__name__)
    print(score + 5)

CSV dialects and delimiters

CSV files can use different delimiters and quoting conventions. The csv module supports dialects and formatting parameters so you can describe the format instead of manually splitting lines. Do not assume that every CSV file uses a comma as its delimiter.

python
import csv
from io import StringIO

data = "name;score\nAda;10\n"

for row in csv.reader(StringIO(data), delimiter=";"):
    print(row)

Keep CSV separate from JSON

JSON and CSV solve different data-format problems. JSON naturally represents nested objects and arrays; CSV is designed around rows and columns of tabular data. Choose the format that matches the data you need to exchange. Neither format replaces File I/O: both operate on file-like objects or other compatible inputs and outputs.

For this lesson, focus on reader(), writer(), DictReader, DictWriter, newline="", explicit encoding at the file boundary, string-valued fields, and basic delimiter handling. Advanced dialect configuration and application-specific type conversion can be learned when needed.

Was this page helpful?

Mark this learning resource complete to track your learning progress.