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 - CSV column names become dictionary keys and each row stores values corresponding to those keys. The read_csv() function from the pandas library reads the CSV file and stores the data in a DataFrame.
Discussions

python - How do I read and write CSV files? - Stack Overflow
How do I read the following 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 How... More on stackoverflow.com
🌐 stackoverflow.com
Reading CSV files
How are you importing the csv? If you are just reading the file as text, then the first row will contain the column name, assuming that is what your csv looks like. If you are using something like the pandas library to read the csv, it is more aware of column headers More on reddit.com
🌐 r/learnpython
5
2
February 23, 2024
Working with CSV files using csv and pandas library in Python
Looks interesting, following your RSS feed to see where what you'll come up with! More on reddit.com
🌐 r/Python
7
60
May 25, 2022
Reading csv file in python
https://docs.python.org/3/library/csv.html is where I'd start. More on reddit.com
🌐 r/learnpython
11
1
April 8, 2019
🌐
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 ...
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)
🌐
Veerpal Brar
veerpalbrar.github.io › blog › 2016 › 08 › 05 › Reading-CSV-Files-with-Python
Reading CSV files with Python
August 5, 2016 - I noticed that the csv library offers two methods for reading a csv file: reader and DictReader. Both read the file row by row and return the data from each row. What vary’s is how they return the data. The reader method returns a list, where each element is a data value from the row.
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:
🌐
Codecademy
codecademy.com › article › python-csv-file
Python CSV Tutorial: Read, Write, and Edit CSV Files | Codecademy
In a CSV file named example.csv, we have the following data: Name,Age,Department Alice,30,HR Bob,24,IT Charlie,28,Finance · The following code opens the example.csv file using the open() function and with read mode.
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › python-read-csv-using-pandas-read_csv
Pandas Read CSV in Python - GeeksforGeeks
Python · JavaScript · Data Science ... To access data from the CSV file, we require a function read_csv() from Pandas that retrieves data in the form of the data frame....
Published   April 28, 2026
🌐
Earthly
earthly.dev › blog › csv-python
How To Read A CSV File In Python - Earthly Blog
July 14, 2023 - Here we are importing the csv library in order to use the .reader() method it contains to help us read the csv file. The with keyword allows us to both open and close the file without having to explicitly close it.
🌐
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 - Python has a built-in csv module that provides the functionality needed for reading and writing CSV files.
🌐
IONOS
ionos.com › digital guide › websites › web development › python pandas read_csv
How to load files into Python with pandas read_csv()
June 20, 2025 - Now, you can load your CSV file to Python pandas using the read_csv() function. Simply pass the filepath to the function.
🌐
YouTube
youtube.com › earthly
Learn HOW to Read CSV Files in Python! - YouTube
Earthly ➤ https://earthly.dev/youtubeIn this Python Data Analysis tutorial, we explore the versatile techniques for reading and processing CSV files using Py...
Published   January 10, 2023
Views   16K
🌐
Analytics Vidhya
analyticsvidhya.com › home › read csv files in python
Read CSV Files in Python - Analytics Vidhya
January 9, 2026 - Steps to read a CSV file using csv reader: ... The .open() method in python is used to open files and return a file object.
🌐
Confessions of a Data Guy
confessionsofadataguy.com › home › 3 (or more) ways to open a csv in python
3 (Or More) Ways to Open a CSV in Python - Confessions of a Data Guy
November 27, 2019 - Not that it matters what’s slower, but sometimes you do run across the 2.5GB csv file, so it’s probably not a bad idea to check out the options. We will be using an open source data set, outstanding student load debt by state. All my code and the file can be found on GitHub. Let’s just open the file, read the rows and split the columns up and call that work. Just open it. Python standard csv module.
🌐
Reddit
reddit.com › r/learnpython › reading csv files
r/learnpython on Reddit: Reading CSV files
February 23, 2024 -

I've been practicing reading CSV files with python the only problem I had that every time I append a certain column to an array if always include the column name.

for x in csv_object:
if isinstance(x[1], str):
    house_price_label = x[1]
if x[1].isdigit():
    house_prices.append(x[1])

🌐
Real Python
realpython.com › python-csv
Reading and Writing CSV Files in Python – Real Python
January 25, 2023 - Learn how to read, process, and parse CSV from text files using Python. You'll see how CSV files work, learn the all-important "csv" library built into Python, and see how CSV parsing works using the "pandas" library.
🌐
Medium
medium.com › casual-inference › the-most-time-efficient-ways-to-import-csv-data-in-python-cc159b44063d
The most (time) efficient ways to import CSV data in Python | by Mihail Yanchev | Casual Inference | Medium
February 7, 2020 - An importnat point here is that pandas.read_csv() can be run with the chunksize option. This will break the input file into chunks instead of loading the whole file into memory. This will reduce the pressure on memory for large input files and ...
🌐
DataCamp
datacamp.com › tutorial › pandas-read-csv
pandas read_csv() Tutorial: Importing Data | DataCamp
March 31, 2026 - There are also tutorials on how ... deeper into the pandas framework. Yes, pandas can read CSV files with different delimiters using the sep parameter in the read_csv() function....