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
All other optional or keyword arguments are passed to the underlying reader instance. If the argument passed to fieldnames is an iterator, it will be coerced to a list. Changed in version 3.6: Returned rows are now of type OrderedDict. Changed in version 3.8: Returned rows are now of type dict. ... >>> import csv >>> with open('names.csv', newline='') as csvfile: ...
🌐
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.
Discussions

utf 8 - Reading a UTF8 CSV file with Python - Stack Overflow
With that statement, you can use later a CSV reader to work with. ... Is it possible that this is Python 3 only? It fails for me, in Python 2. More on stackoverflow.com
🌐 stackoverflow.com
Writing to_csv with progress bar (using chunks?)
Maybe Dask is what you're looking for. A Dask DataFrame is a large parallel dataframe composed of many smaller Pandas dataframes, split along the index. These pandas dataframes may live on disk for larger-than-memory computing on a single machine, or on many different machines in a cluster. progress bar included And if you need persistence, but not necessarily CSV, formats like hdf5, parquet and feather are a lot faster. More on reddit.com
🌐 r/learnpython
7
1
September 4, 2017
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
People also ask

How do I start reading CSV files in Python?
You can read a CSV file in Python using either the built-in csv module or the pandas library. Both allow you to open and process the file, but pandas is better for large or complex data.
🌐
wscubetech.com
wscubetech.com › resources › python › reading-csv-files
Read CSV Files in Python: With Examples
Can I read a CSV file in Python without using pandas?
Yes, you can use the built-in csv.reader() function to read CSV files without pandas. It works well for basic tasks and lets you process each row one by one.
🌐
wscubetech.com
wscubetech.com › resources › python › reading-csv-files
Read CSV Files in Python: With Examples
How can I read multiple CSV files in Python at once?
You can loop through a list of file names and use csv.reader() or pandas.read_csv() inside the loop. This helps when you need to combine or process many files at once.
🌐
wscubetech.com
wscubetech.com › resources › python › reading-csv-files
Read CSV Files in Python: With Examples
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)
🌐
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 reader method tended to finish around a thousandth of a second faster than the DictReader method. If you were planning on reading large CSV files, those few extra thousandths of a second could make a big difference for efficiency. On the other hand, if the CSV file is not large its probably better to use DictReader as it provides better readability. Say, for example, you want to print the first column of every row, which holds the data ID.
Find elsewhere
🌐
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
🌐
Python Morsels
pythonmorsels.com › csv-reading
Reading a CSV file in Python - Python Morsels
January 23, 2023 - This usually involves passing reader a file object, because files are iterables in Python, and as we loop over them, we'll get back each line in our file (see reading a file line-by-line in Python). Here we have a CSV file called penguins_small.csv:
🌐
WsCube Tech
wscubetech.com › resources › python › reading-csv-files
Read CSV Files in Python: With Examples
October 1, 2025 - Learn how to read CSV files in Python with examples. This guide covers simple methods and practical code to handle CSV data efficiently using Python.
🌐
Analytics Vidhya
analyticsvidhya.com › home › read csv files in python
Read CSV Files in Python - Analytics Vidhya
January 9, 2026 - A. There are many ways to read CSV files as plain text in Python including using csv.reader, .readlines(), pandas, or csv.DictReader.
🌐
Learn Python
learnpython.org › en › Parsing_CSV_Files
Parsing CSV Files - Learn Python - Free Interactive Python Tutorial
Your task is to create a Python ... csv # Open the input CSV file with open('inputfile.csv', mode='r') as infile: reader = csv.reader(infile) # Open the output CSV file with open('outputfile.csv', mode='w') as outfile: writer ...
🌐
Note.nkmk.me
note.nkmk.me › home › python
Read and Write CSV Files in Python | note.nkmk.me
August 6, 2023 - For example, you can get data for each row as a list with a for loop. with open('data/src/sample.csv') as f: reader = csv.reader(f) for row in reader: print(row) # ['11', '12', '13', '14'] # ['21', '22', '23', '24'] # ['31', '32', '33', '34']
🌐
w3resource
w3resource.com › python › python-handling-csv-files-with-examples.php
Python CSV Files: Handling CSV files using the csv Module
Similar to 'DictReader', the 'csv.DictWriter' class is used to write dictionaries to a CSV file. You need to specify the fieldnames (i.e., column headers) when creating the 'DictWriter' object. Example 4: Writing Data with a Header to a CSV File
🌐
Earthly
earthly.dev › blog › csv-python
How To Read A CSV File In Python - Earthly Blog
July 14, 2023 - The first by using the csv library, and the second by using the pandas library. import csv with open("./bwq.csv", 'r') as file: csvreader = csv.reader(file) for row in csvreader: print(row)
🌐
ThePythonGuru
thepythonguru.com › python-how-to-read-and-write-csv-files › index.html
Python: How to read and write CSV files - ThePythonGuru.com
January 7, 2020 - Before we start reading and writing ... reading how to read and write file in Python. The csv module is used for reading and writing files. It mainly provides following classes and functions: ... Let's start with the reader() function....
🌐
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 information: Name,Age,Department Alice,30,HR Bob,24,IT Charlie,28,Finance · 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.
🌐
DigitalOcean
digitalocean.com › community › tutorials › parse-csv-files-in-python
How to Parse CSV Files in Python | DigitalOcean
August 4, 2022 - Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev ... While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial. ... Nice tutorial In first example of reading csv, we try to close file and are using with statement too.
🌐
GeeksforGeeks
geeksforgeeks.org › python › working-csv-files-python
Working with csv files in Python - GeeksforGeeks
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 a file object. In this example, we first open the CSV file in READ mode, file object is converted to csv.reader object and further operation ...
Published   August 5, 2025
🌐
Python Beginners
python-adv-web-apps.readthedocs.io › en › latest › csv.html
CSV Files — Python Beginners documentation
The following example script uses a CSV file named presidents.csv. It contains 46 rows: one row for each U.S. president, plus a header row at the top. The script opens the CSV and then can get all rows from it. Above, the top rows of the CSV file as seen in Excel. ... Note that in line 13 above, row is a Python list, and so we can use list indexes to get only the second item — row[1] — and the sixth item — row[5]. When we use csv.reader(), each row from the CSV file is a Python list of strings.
Top answer
1 of 10
119

The .encode method gets applied to a Unicode string to make a byte-string; but you're calling it on a byte-string instead... the wrong way 'round! Look at the codecs module in the standard library and codecs.open in particular for better general solutions for reading UTF-8 encoded text files. However, for the csv module in particular, you need to pass in utf-8 data, and that's what you're already getting, so your code can be much simpler:

import csv

def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
    csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
    for row in csv_reader:
        yield [unicode(cell, 'utf-8') for cell in row]

filename = 'da.csv'
reader = unicode_csv_reader(open(filename))
for field1, field2, field3 in reader:
  print field1, field2, field3 

PS: if it turns out that your input data is NOT in utf-8, but e.g. in ISO-8859-1, then you do need a "transcoding" (if you're keen on using utf-8 at the csv module level), of the form line.decode('whateverweirdcodec').encode('utf-8') -- but probably you can just use the name of your existing encoding in the yield line in my code above, instead of 'utf-8', as csv is actually going to be just fine with ISO-8859-* encoded bytestrings.

2 of 10
116

Python 2.X

There is a unicode-csv library which should solve your problems, with added benefit of not naving to write any new csv-related code.

Here is a example from their readme:

>>> import unicodecsv
>>> from cStringIO import StringIO
>>> f = StringIO()
>>> w = unicodecsv.writer(f, encoding='utf-8')
>>> w.writerow((u'é', u'ñ'))
>>> f.seek(0)
>>> r = unicodecsv.reader(f, encoding='utf-8')
>>> row = r.next()
>>> print row[0], row[1]
é ñ

Python 3.X

In python 3 this is supported out of the box by the build-in csv module. See this example:

import csv
with open('some.csv', newline='', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)