Here are some minimal complete examples how to read CSV files and how to write CSV files with Python.

Pure Python:

import csv

# Define data
data = [
    (1, "A towel,", 1.0),
    (42, " it says, ", 2.0),
    (1337, "is about the most ", -1),
    (0, "massively useful thing ", 123),
    (-2, "an interstellar hitchhiker can have.", 3),
]

# Write CSV file
with open("test.csv", "wt") as fp:
    writer = csv.writer(fp, delimiter=",")
    # writer.writerow(["your", "header", "foo"])  # write header
    writer.writerows(data)

# Read CSV file
with open("test.csv") as fp:
    reader = csv.reader(fp, delimiter=",", quotechar='"')
    # next(reader, None)  # skip the headers
    data_read = [row for row in reader]

print(data_read)

After that, the contents of data_read are

[['1', 'A towel,', '1.0'],
 ['42', ' it says, ', '2.0'],
 ['1337', 'is about the most ', '-1'],
 ['0', 'massively useful thing ', '123'],
 ['-2', 'an interstellar hitchhiker can have.', '3']]

Please note that CSV reads only strings. You need to convert to the column types manually.

A Python 2+3 version was here before (link), but Python 2 support is dropped. Removing the Python 2 stuff massively simplified this answer.

Related

  • How do I write data into csv format as string (not file)?
  • How can I use io.StringIO() with the csv module?: This is interesting if you want to serve a CSV on-the-fly with Flask, without actually storing the CSV on the server.

mpu

Have a look at my utility package mpu for a super simple and easy to remember one:

import mpu.io
data = mpu.io.read('example.csv', delimiter=',', quotechar='"', skiprows=None)
mpu.io.write('example.csv', data)

Pandas

import pandas as pd

# Read the CSV into a pandas data frame (df)
#   With a df you can do many things
#   most important: visualize data with Seaborn
df = pd.read_csv('myfile.csv', sep=',')
print(df)

# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]

# or export it as a list of dicts
dicts = df.to_dict().values()

See read_csv docs for more information. Please note that pandas automatically infers if there is a header line, but you can set it manually, too.

If you haven't heard of Seaborn, I recommend having a look at it.

Other

Reading CSV files is supported by a bunch of other libraries, for example:

  • dask.dataframe.read_csv
  • spark.read.csv

Created CSV file

1,"A towel,",1.0
42," it says, ",2.0
1337,is about the most ,-1
0,massively useful thing ,123
-2,an interstellar hitchhiker can have.,3

Common file endings

.csv

Working with the data

After reading the CSV file to a list of tuples / dicts or a Pandas dataframe, it is simply working with this kind of data. Nothing CSV specific.

Alternatives

  • JSON: Nice for writing human-readable data; VERY commonly used (read & write)
  • CSV: Super simple format (read & write)
  • YAML: Nice to read, similar to JSON (read & write)
  • pickle: A Python serialization format (read & write)
  • MessagePack (Python package): More compact representation (read & write)
  • HDF5 (Python package): Nice for matrices (read & write)
  • XML: exists too *sigh* (read & write)

For your application, the following might be important:

  • Support by other programming languages
  • Reading / writing performance
  • Compactness (file size)

See also: Comparison of data serialization formats

In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python

Answer from Martin Thoma on Stack Overflow
🌐
Python
docs.python.org › 3 › library › csv.html
csv — CSV File Reading and Writing
The csv module’s reader and writer objects read and write sequences. Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes. ... The Python Enhancement Proposal which proposed this addition to Python.
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › reading-csv-files-in-python
Reading CSV files in Python - GeeksforGeeks
May 25, 2026 - The csv.reader() function reads the CSV file line by line and returns each row as a list.
🌐
Veerpal Brar
veerpalbrar.github.io › blog › 2016 › 08 › 05 › Reading-CSV-Files-with-Python
Reading CSV files with Python
August 5, 2016 - The csv library has a lot of methods that make reading from and writing to CSV files simple and easy. It handles all the nuances of reading and writing to a csv file, leaving you to work with the data. I noticed that the csv library offers two methods for reading a csv file: reader and DictReader.
Top answer
1 of 9
127

Here are some minimal complete examples how to read CSV files and how to write CSV files with Python.

Pure Python:

import csv

# Define data
data = [
    (1, "A towel,", 1.0),
    (42, " it says, ", 2.0),
    (1337, "is about the most ", -1),
    (0, "massively useful thing ", 123),
    (-2, "an interstellar hitchhiker can have.", 3),
]

# Write CSV file
with open("test.csv", "wt") as fp:
    writer = csv.writer(fp, delimiter=",")
    # writer.writerow(["your", "header", "foo"])  # write header
    writer.writerows(data)

# Read CSV file
with open("test.csv") as fp:
    reader = csv.reader(fp, delimiter=",", quotechar='"')
    # next(reader, None)  # skip the headers
    data_read = [row for row in reader]

print(data_read)

After that, the contents of data_read are

[['1', 'A towel,', '1.0'],
 ['42', ' it says, ', '2.0'],
 ['1337', 'is about the most ', '-1'],
 ['0', 'massively useful thing ', '123'],
 ['-2', 'an interstellar hitchhiker can have.', '3']]

Please note that CSV reads only strings. You need to convert to the column types manually.

A Python 2+3 version was here before (link), but Python 2 support is dropped. Removing the Python 2 stuff massively simplified this answer.

Related

  • How do I write data into csv format as string (not file)?
  • How can I use io.StringIO() with the csv module?: This is interesting if you want to serve a CSV on-the-fly with Flask, without actually storing the CSV on the server.

mpu

Have a look at my utility package mpu for a super simple and easy to remember one:

import mpu.io
data = mpu.io.read('example.csv', delimiter=',', quotechar='"', skiprows=None)
mpu.io.write('example.csv', data)

Pandas

import pandas as pd

# Read the CSV into a pandas data frame (df)
#   With a df you can do many things
#   most important: visualize data with Seaborn
df = pd.read_csv('myfile.csv', sep=',')
print(df)

# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]

# or export it as a list of dicts
dicts = df.to_dict().values()

See read_csv docs for more information. Please note that pandas automatically infers if there is a header line, but you can set it manually, too.

If you haven't heard of Seaborn, I recommend having a look at it.

Other

Reading CSV files is supported by a bunch of other libraries, for example:

  • dask.dataframe.read_csv
  • spark.read.csv

Created CSV file

1,"A towel,",1.0
42," it says, ",2.0
1337,is about the most ,-1
0,massively useful thing ,123
-2,an interstellar hitchhiker can have.,3

Common file endings

.csv

Working with the data

After reading the CSV file to a list of tuples / dicts or a Pandas dataframe, it is simply working with this kind of data. Nothing CSV specific.

Alternatives

  • JSON: Nice for writing human-readable data; VERY commonly used (read & write)
  • CSV: Super simple format (read & write)
  • YAML: Nice to read, similar to JSON (read & write)
  • pickle: A Python serialization format (read & write)
  • MessagePack (Python package): More compact representation (read & write)
  • HDF5 (Python package): Nice for matrices (read & write)
  • XML: exists too *sigh* (read & write)

For your application, the following might be important:

  • Support by other programming languages
  • Reading / writing performance
  • Compactness (file size)

See also: Comparison of data serialization formats

In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python

2 of 9
2

If you are working with CSV data and want a solution with a smaller footprint than pandas, you can try my package, littletable. Can be pip-installed, or just dropped in as a single .py file with your own code, so very portable and suitable for serverless apps.

Reading CSV data is as simple as calling csv_import:

data = """\
1,"A towel,",1.0
42," it says, ",2.0
1337,is about the most ,-1
0,massively useful thing ,123
-2,an interstellar hitchhiker can have.,3"""

import littletable as lt
tbl = lt.Table().csv_import(data, fieldnames="number1,words,number2".split(','))
tbl.present()

Prints:

  Number1   Words                                  Number2  
 ────────────────────────────────────────────────────────── 
  1         A towel,                               1.0      
  42         it says,                              2.0      
  1337      is about the most                      -1       
  0         massively useful thing                 123      
  -2        an interstellar hitchhiker can have.   3    

(littletable uses the rich module for presenting Tables.)

littletable doesn't automatically try to convert numeric data, so a numeric transform function is needed for the numeric columns.

def get_numeric(s):
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            return s

tbl = lt.Table().csv_import(
    data,
    fieldnames="number1,words,number2".split(','),
    transforms={}.fromkeys("number1 number2".split(), get_numeric)
)
tbl.present()

This gives:

  Number1   Words                                  Number2  
 ────────────────────────────────────────────────────────── 
        1   A towel,                                   1.0  
       42    it says,                                  2.0  
     1337   is about the most                           -1  
        0   massively useful thing                     123  
       -2   an interstellar hitchhiker can have.         3  

The numeric columns are right-justified instead of left-justified.

littletable also has other ORM-ish features, such as indexing, joining, pivoting, and full-text search. Here is a table of statistics on the numeric columns:

tbl.stats("number1 number2".split()).present()

  Name       Mean   Min    Max   Variance              Std_Dev   Count   Missing  
 ──────────────────────────────────────────────────────────────────────────────── 
  number1   275.6    -2   1337   352390.3    593.6247130974249       5         0  
  number2    25.6    -1    123     2966.8   54.468339427597755       5         0  

or transposed:

tbl.stats("number1 number2".split(), by_field=False).present()

  Stat                 Number1              Number2 
 ─────────────────────────────────────────────────── 
  mean                   275.6                 25.6
  min                       -2                   -1
  max                     1337                  123
  variance            352390.3               2966.8
  std_dev    593.6247130974249   54.468339427597755
  count                      5                    5
  missing                    0                    0

Other formats can be output too, such as Markdown:

print(tbl.stats("number1 number2".split(), by_field=False).as_markdown())

| stat | number1 | number2 |
|---|---:|---:|
| mean | 275.6 | 25.6 |
| min | -2 | -1 |
| max | 1337 | 123 |
| variance | 352390.3 | 2966.8 |
| std_dev | 593.6247130974249 | 54.468339427597755 |
| count | 5 | 5 |
| missing | 0 | 0 |

Which would render from Markdown as

stat number1 number2
mean 275.6 25.6
min -2 -1
max 1337 123
variance 352390.3 2966.8
std_dev 593.6247130974249 54.468339427597755
count 5 5
missing 0 0

Lastly, here is a text search on the words for any entry with the word "hitchhiker":

tbl.create_search_index("words")
for match in tbl.search.words("hitchhiker"):
    print(match)

Prints:

   namespace(number1=-2, words='an interstellar hitchhiker can have.', number2=3)
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.read_csv.html
pandas.read_csv — pandas 3.0.4 documentation
A local file could be: file://localhost/path/to/table.csv. If you want to pass in a path object, pandas accepts any os.PathLike. By file-like object, we refer to objects with a read() method, such as a file handle (e.g. via builtin open function) or StringIO. ... Character or regex pattern to treat as the delimiter. If sep=None, the C engine cannot automatically detect the separator, but the Python parsing engine can, meaning the latter will be used and automatically detect the separator from only the first valid row of the file by Python’s builtin sniffer tool, csv.Sniffer.
🌐
University of Washington
courses.cs.washington.edu › courses › cse160 › 22au › computing › csv-parsing.html
How to parse csv formatted files using csv.DictReader
When you iterate over a CSV file using csv.DictReader, each iteration of the loop produces a dictionary mapping keys that are strings to values that are strings. They keys are the names of the columns (from the first row of the file, which is skipped over), and the values are the data from the row being read.
Find elsewhere
🌐
Python Morsels
pythonmorsels.com › csv-reading
Reading a CSV file in Python - Python Morsels
January 23, 2023 - Let's use Python's built-in open function to open our file for reading. ... When we loop over a csv.reader object, the reader will loop over the file object that we originally gave it and convert each line in our file to a list of strings:
🌐
W3Schools
w3schools.com › python › pandas › pandas_csv.asp
Pandas Read CSV
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP W3.CSS C C++ C# HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS · Pandas HOME Pandas Intro Pandas Getting Started Pandas Series Pandas DataFrames Pandas Read CSV Pandas Read JSON Pandas Analyzing Data
🌐
Real Python
realpython.com › python-csv
Reading and Writing CSV Files in Python – Real Python
January 25, 2023 - Any language that supports text file input and string manipulation (like Python) can work with CSV files directly. The csv library provides functionality to both read from and write to CSV files.
🌐
Reddit
reddit.com › r/learnpython › csv.reader() is confusing me
r/learnpython on Reddit: csv.reader() is confusing me
August 7, 2023 -

Hello. Thank you all in advance for helping me.

So I’m reading the book “Python Crash Course” and, going through the chapter 16: downloading data, I got confused with csv.reader. The objective is to read the data of meteorological station, more specific the headers of the file to obtain this:

Output:

0 STATION 1 NAME 2 DATE 3 AWND 4 PGTM 5 PRCP 6 TAVG 7 TMAX 8 TMIN 9 WDF2 10 WDF5 11 WSF2 12 WSF5 13 WT01 14 WT02 15 WT04 16 WT05 17 WT08 18 WT09

The code to obtain the output is:

import matplotlib.pyplot as plt import csv from pathlib import Path

path = Path('weather_data/sitka_weather_2021_full.csv') lines = path.read_text().splitlines() print(lines)

reader = csv.reader(lines) header_row = next(reader)

for index, collumn_header in enumerate(header_row): print(index, collumn_header)

What I don’t understand is the use of csv.reader(lines) and the next(reader). I searched but I don’t really understand how python only reads the first object of the line of the file.

🌐
DEV Community
dev.to › jenad88 › day-39-40-reading-and-writing-csv-files-in-python-4j3o
Day 39-40: Reading and Writing CSV Files in Python - DEV Community
May 20, 2023 - Here, we are using the open() function to open the CSV file in 'read' mode ('r'). Then, this file object is passed to the csv.reader(), which returns a reader object that we iterate over, printing each row.
🌐
GeeksforGeeks
geeksforgeeks.org › python › working-csv-files-python
Working with csv files in Python - GeeksforGeeks
Below are some operations that we perform while working with Python CSV files in Python · Reading from a CSV file is done using the reader object. The CSV file is opened as a text file with Python’s built-in open() function, which returns ...
Published   August 5, 2025
🌐
Real Python
realpython.com › ref › stdlib › csv
csv | Python Standard Library – Real Python
The Python csv module provides functionality to read from and write to CSV (comma-separated values) files, which are a common format for data interchange. The module offers both high-level and low-level interfaces for handling CSV data.
🌐
Earthly
earthly.dev › blog › csv-python
How To Read A CSV File In Python - Earthly Blog
July 14, 2023 - Learn how to read a CSV file in Python using both the `csv` and `pandas` libraries. Discover the different methods and possible delimiter issues, a...
🌐
Codecademy
codecademy.com › article › python-csv-file
Python CSV Tutorial: Read, Write, and Edit CSV Files | Codecademy
We write a Python script to read this CSV file and print its contents like so: ... In this code, we create a CSV reader object using csv.reader(file), which reads a CSV file and returns each row as a list of strings.
🌐
Python.org
discuss.python.org › python help
How can I retrieve a specific element in a CSV file? - Python Help - Discussions on Python.org
October 3, 2022 - Hi, I have a CSV file from which I want to retrieve a specific element, to be precise the one contained in a certain column and in the last row (or the first, starting from the bottom) to have a certain string as the first element. I’ll give a simplified practical example, where instead of ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › reading-and-writing-csv-files-in-python
Reading and Writing CSV Files in Python - GeeksforGeeks
July 15, 2025 - To read a CSV file, Python provides the csv.reader class, which reads data in a structured format. The first step involves opening the CSV file using the open() function in read mode ('r').
🌐
Pythontic
pythontic.com › fileformats › csvreader › introduction
CSV Reader in Python with Example | Pythontic.com
This example reads a CSV file containing stock quotes where the delimiter is a comma and no special end of line character is specified. The parameter to the python csv.reader object is a fileobject representing the CSV file with the comma-separated fields as records.
🌐
PyPI
pypi.org › project › csv-reader
csv-reader · PyPI
August 14, 2020 - I developed this library for fun. If anyone wants to contribute, feel free to contact me or open an issue. This library uses the built-in csv module · Type this into your command prompt: pip install csv-reader...
      » pip install csv-reader
    
Published   Aug 14, 2020
Version   1.2.0
🌐
Python Beginners
python-adv-web-apps.readthedocs.io › en › latest › csv.html
CSV Files — Python Beginners documentation
Create a CSV reader object and assign it to a new variable. Use a for-loop to read from all rows in the CSV. Close the file. The csv.DictReader() method is used to convert a CSV file to a Python dictionary. You read from an existing CSV and create a Python dictionary from it.