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
Note that unlike the DictReader class, the fieldnames parameter of the DictWriter class is not optional. If the argument passed to fieldnames is an iterator, it will be coerced to a list. ... import csv with open('names.csv', 'w', newline='') as csvfile: fieldnames = ['first_name', 'last_name'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'}) writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'}) writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
🌐
DEV Community
dev.to › thumbone › dumping-data-with-pythons-csv-dictwriter-1g0
Dumping Data with Python's CSV DictWriter - DEV Community
May 16, 2025 - I really love Python's csv module. But I do wish it was a little better documented. The DictWriter lets you write CSV files very neatly and semantically by defining each row as a Python dict.
Discussions

python - How do I read and write CSV files? - Stack Overflow
There are also dictionary wrapper objects - csv.DictReader and csv.DictWriter - which return and write dictionary formatted data. More on stackoverflow.com
🌐 stackoverflow.com
python - How do I make a proper csv file using DictWriter method - Stack Overflow
How do I make a 3 or more column csv file using the example? import csv fruits = ["apple", "banana", "grape", "orange"] vegetables = ["onion", " More on stackoverflow.com
🌐 stackoverflow.com
CSV writer help
I wrote a tutorial for anyone wondering ... and csv.DictWriter with examples of quoting and dialects. Check it out! ... I'm sick of excel. I need a good, GUI-based CSV writer to make input files for my scripts. Any good options? ... Why csv.writer leaves empty space in between rows, like I mentioned below? and how can I prevent this? ... Should I learn python using ... More on reddit.com
🌐 r/learnpython
8
2
August 20, 2020
Python: Writing a Dict to CSV - Stack Overflow
I am attempting to run regression against a really large csv file. However, many of the columns were constructed to represent binary situations, and only the 1 values got logged in the csv. The val... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › writing-csv-files-in-python
Writing CSV files in Python - GeeksforGeeks
July 12, 2025 - Below are the ways by which we can write CSV files in Python: The csv.DictWriter class maps dictionaries onto output rows, allowing you to write data where each row is represented by a dictionary.
🌐
Paigeniedringhaus
paigeniedringhaus.com › blog › create-a-custom-formatted-csv-from-python-data
Create a Custom Formatted CSV from Python Data | Paige Niedringhaus
April 19, 2024 - DictWriter - an object like a writer but it maps dictionaries to output rows. This object requires a fieldnames parameter that is a sequence of keys which identifies the order in which values in the dictionary are passed to the writerow() method.
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)
🌐
Python Morsels
pythonmorsels.com › csv-writing
Writing a CSV file - Python Morsels
February 14, 2023 - >>> import csv >>> csv.DictWriter <class 'csv.DictWriter'>
Find elsewhere
🌐
Vertabelo Academy
academy.vertabelo.com › course › python-csv › writing › writing › dictwriter-with-writeheader
Read and Write CSV in Python | Learn Python | Vertabelo Academy
You may have noticed that DictWriter doesn't insert a header row by default. You have to add it manually by invoking the writeheader() method: data_to_save = [ {'Author':'John Smith', 'Title':'Keep holding on', 'Pages':'326'}, {'Author':'Erica Coleman', 'Title':'The beauty is the beast', 'Pages':'274'} ] with open('books.csv', mode='w', newline='') as csv_file: csv_writer = csv.DictWriter(csv_file, fieldnames=['Author','Title','Pages']) csv_writer.writeheader() for row in data_to_save: csv_writer.writerow(row)
🌐
Medium
medium.com › @3valuedlogic › using-python-csv-4-dictwriter-7812e2200721
Using Python CSV #4 — DictWriter. Basic Usage of DictWriter | by David W. Agler | Medium
December 23, 2022 - In essence, csv.DictWriter creates a spreadsheet and maps lists of dictionaries to rows of a spreadsheet. Let’s start with a simple example. First, let’s say we have a list of dictionaries.
🌐
CodeSignal
codesignal.com › learn › courses › parsing-table-data › lessons › writing-table-data-to-csv-files-using-python
Writing Table Data to CSV Files Using Python
Welcome to the final lesson in our course focused on working with different files as data sources. In this lesson, you will learn how to write table data to a CSV file using Python's built-in csv module. Throughout this course, you have been introduced to various aspects of handling table data.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Read and Write CSV Files in Python | note.nkmk.me
August 6, 2023 - with open('data/temp/sample_dictwriter_ignore.csv', 'w') as f: writer = csv.DictWriter(f, ['a', 'c'], extrasaction='ignore') writer.writeheader() writer.writerows([d1, d2]) with open('data/temp/sample_dictwriter_ignore.csv') as f: print(f.read()) # a,c # 1,3 # 10,30 ... The default is extrasaction='raise', which throws a ValueError. The third-party library NumPy offers more flexible manipulation of multidimensional arrays. It's also possible to convert between NumPy arrays (numpy.ndarray) and Python built-in lists.
🌐
Reddit
reddit.com › r/learnpython › csv writer help
r/learnpython on Reddit: CSV writer help
August 20, 2020 - I wrote a tutorial for anyone wondering how to read/write CSV files using csv.reader, csv.writer and csv.DictWriter with examples of quoting and dialects. Check it out! ... I'm sick of excel. I need a good, GUI-based CSV writer to make input files for my scripts. Any good options? ... Why csv.writer leaves empty space in between rows, like I mentioned below? and how can I prevent this? ... Should I learn python using documentation.
Top answer
1 of 3
3
for row in r:
   for val in row:
      if len(row[val])<1:
         row[val]='0'
   w.write_row(row)

you have to actually tell it to write the row

2 of 3
1

If you really want to use the csv module there are multiple errors in your code you need to fix, you need to pass the fieldnames to csv.DictWriter then write them and the length of the empty string will be 1 so csv.DictWriter will never be True so nothing will be changed:

with open('in.csv', 'r') as infile, open('Fixed.csv', 'w') as outfile:
    r = csv.DictReader(infile)
    w = csv.DictWriter(outfile, fieldnames=r.fieldnames)
    w.writeheader()
    for row in r:
        for k, v in row.items():
            if v == "''":
                row[k] = "0"
        w.writerow(row)

To change the original file it would actually be easier just use str.replace and open the file without the csv module, to change the original file you can use fileinput with inplace=True:

import fileinput
import sys

for line in fileinput.input("in.csv",inplace=True):
    sys.stdout.write(line.replace("''","0"))

Output:

One,Two,Three,Four
1,0,0,1
0,0,1,0
1,0,1,0
0,0,0,1

Or using a NamedTemporaryFile with shutil.move, writing to the tempfile the replacing the original file with the updated file using move:

from tempfile import NamedTemporaryFile

from shutil import move

with open('TestCSV.csv', 'r') as infile, NamedTemporaryFile(dir=".", delete=False) as  outfile:
    for line in infile:
        outfile.write(line.replace("''", "0"))

move(outfile.name,'TestCSV.csv')

Or if you want a new file just do the same using file.write:

with open('TestCSV.csv','r') as infile,open('Fixed.csv','w') as outfile:
     for line in infile:
         outfile.write(line.replace("''","0"))

You only have either an empty string or a "1" in each line so it is simpler just to replace the empty strings.

You could also do it quite easily with pandas using a Dataframe and df.replace if you intend to actually create a df with your data:

df = pd.read_csv("in.csv")
df.replace("''","0",inplace=True)
print(df)

  One Two Three Four
0   1   0     0    1
1   0   0     1    0
2   1   0     1    0
3   0   0     0    1
# work on df
.......
# save results to csv
df.to_csv("fixed.csv",index=False)

Output:

One,Two,Three,Four
1,0,0,1
0,0,1,0
1,0,1,0
0,0,0,1
🌐
Stack Overflow
stackoverflow.com › questions › 60808725 › what-is-the-difference-between-dictwriter-vs-write-in-python
file - What is the difference between .DictWriter() vs .write() in Python? - Stack Overflow
csv.writer and csv.DictWriter are specialised to transforms rows (respectively lists and dicts) into CSV data, properly escaped according to the dialect.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-write-dictionary-of-list-to-csv
Python - Write dictionary of list to CSV - GeeksforGeeks
July 23, 2025 - # import the csv package import csv # create a csv file with desired name #and store it in a variable with open('test.csv', 'w') as testfile: # store the desired header row as a list # and store it in a variable fieldnames = ['first_field', 'second_field', 'third_field'] # pass the created csv file and the header # rows to the Dictwriter function writer = csv.DictWriter(testfile, fieldnames=fieldnames) # Now call the writeheader function, # this will write the specified rows as # headers of the csv file writer.writeheader()
🌐
jdhao's digital space
jdhao.github.io › 2018 › 05 › 13 › read-write-csv-file-with-header
How to Read and Write CSV Files in Python · jdhao's digital space
September 29, 2022 - In order to write to files in CSV format, we build a CSV writer, then write to a file using this writer.
🌐
X
x.com › testdrivenio › status › 1347956052935933954
Python tip: You can use DictWriter to make a CSV file from ...
Python tip: You can use DictWriter to make a CSV file from a list of dictionaries An example · 11:19 AM · Jan 9, 2021 · 2 · 8 · 72 · 15 · Sign up now to get your own personalized timeline! Sign up with GoogleSign up with Google. Opens in new tab · Sign up with Apple ·
🌐
Euron
euron.one › community › posts › cbb76926-d6ef-4a60-a11a-3f160dd4ddf1
CSV File Handling in Python: csv.reader & DictWriter - Euron Daily | Euron Community
March 23, 2026 - Hey everyone! Let's look at how to handle CSV files in Python, focusing on `csv.reader` and `DictWriter`. ## csv.reader `csv.reader` helps you read data from
🌐
Python Beginners
python-adv-web-apps.readthedocs.io › en › latest › csv.html
CSV Files — Python Beginners documentation
You can read generally about Python dictionaries here: Dictionaries ... The csv.DictWriter() method will write to a CSV file using rows of data that are already formatted as dictionaries.