100% found this document useful (1 vote)
22 views11 pages

Python CSV - Read, Write CSV in Python

Uploaded by

Juan Cuartas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
22 views11 pages

Python CSV - Read, Write CSV in Python

Uploaded by

Juan Cuartas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ZetCode

All Spring Boot Python C# Java JavaScript Subscribe

Python CSV tutorial - read write CSV


last modified July 6, 2020

Python CSV tutorial shows how to read and write CSV data with Python csv module.

CSV
CSV (Comma Separated Values) is a very popular import and export data format used in
spreadsheets and databases. Each line in a CSV file is a data record. Each record consists of one or
more fields, separated by commas. While CSV is a very simple data format, there can be many
differences, such as different delimiters, new lines, or quoting characters.

Python csv module


The csv module implements classes to read and write tabular data in CSV format. 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.

Python CSV methods


The following table shows Python csv methods:

Method Description

[Link] returns a reader object which iterates over lines of a CSV file

[Link] returns a writer object which writes data into CSV file

csv.register_dialect registers a CSV dialect

csv.unregister_dialect unregisters a CSV dialect

csv.get_dialect returns a dialect with the given name

csv.list_dialects returns all registered dialects

csv.field_size_limit returns the current maximum field size allowed by the parser

Using Python csv module


import csv

To use Python CSV module, we import csv.

Python CSV reader


The [Link]() method returns a reader object which iterates over lines in the given CSV file.

$ cat [Link]
16,6,4,12,81,6,71,6

The [Link] file contains numbers.

read_csv.py
#!/usr/bin/python3

import csv

f = open('[Link]', 'r')

with f:

reader = [Link](f)

for row in reader:


for e in row:
print(e)

In the code example, we open the [Link] for reading and read its contents.

reader = [Link](f)

We get the reader object.

for row in reader:


for e in row:
print(e)

With two for loops, we iterate over the data.

$ ./read_csv.py
16
6
4
12
81
6
71
6

This is the output of the example.


Python CSV reader with different delimiter
The [Link]() method allows to use a different delimiter with its delimiter attribute.

$ cat [Link]
pen|cup|bottle
chair|book|tablet

The [Link] contains values separated with '|' character.

read_csv.py
#!/usr/bin/python3

import csv

f = open('[Link]', 'r')

with f:

reader = [Link](f, delimiter="|")

for row in reader:


for e in row:
print(e)

The code example reads and displays data from a CSV file that uses a '|' delimiter.

$ ./read_csv2.py
pen
cup
bottle
chair
book
tablet

This is the output of the example.

Python CSV DictReader


The [Link] class operates like a regular reader but maps the information read into a
dictionary. The keys for the dictionary can be passed in with the fieldnames parameter or inferred
from the first row of the CSV file.

$ cat [Link]
min,avg,max
1, 5.5, 10
2, 3.5, 5

The first line of the file consists of dictionary keys.

read_csv_dictionary.py
#!/usr/bin/python3

# read_csv3.py

import csv

f = open('[Link]', 'r')
with f:

reader = [Link](f)

for row in reader:


print(row['min'], row['avg'], row['max'])

The example reads the values from the [Link] file using the [Link].

Integramos la cienciacon
amor

Comprometidos con Abrazar La Vida de


cada uno de nuestros pacientes.

Clínica Vida Abrir

for row in reader:


print(row['min'], row['avg'], row['max'] )

The row is a Python dictionary and we reference the data with the keys.

Python CSV writer


The [Link]() method returns a writer object which converts the user's data into delimited
strings on the given file-like object.

write_csv.py
#!/usr/bin/python3

import csv

nms = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]

f = open('[Link]', 'w')

with f:

writer = [Link](f)

for row in nms:


[Link](row)

The script writes numbers into the [Link] file. The writerow() method writes a row of
data into the specified file.

$ cat [Link]
1,2,3,4,5,6
7,8,9,10,11,12

It is possible to write all data in one shot. The writerows() method writes all given rows to the
CSV file.

write_csv2.py
#!/usr/bin/python3

import csv

nms = [[1, 2, 3], [7, 8, 9], [10, 11, 12]]

f = open('[Link]', 'w')

with f:

writer = [Link](f)
[Link](nms)
The code example writes three rows of numbers into the file using the writerows() method.

Python CSV DictWriter


The [Link] class operates like a regular writer but maps Python dictionaries into CSV
rows. The fieldnames parameter is a sequence of keys that identify the order in which values in
the dictionary passed to the writerow() method are written to the CSV file.

write_csv_dictionary.py
#!/usr/bin/python3

import csv

f = open('[Link]', 'w')

with f:

fnames = ['first_name', 'last_name']


writer = [Link](f, fieldnames=fnames)

[Link]()
[Link]({'first_name' : 'John', 'last_name': 'Smith'})
[Link]({'first_name' : 'Robert', 'last_name': 'Brown'})
[Link]({'first_name' : 'Julia', 'last_name': 'Griffin'})

The example writes the values from Python dictionaries into the CSV file using the
[Link].

writer = [Link](f, fieldnames=fnames)

New [Link] is created. The header names are passed to the fieldnames parameter.

[Link]()
The writeheader() method writes the headers to the CSV file.

[Link]({'first_name' : 'John', 'last_name': 'Smith'})

Integramos la cienciacon
amor

Comprometidos con Abrazar La Vida de


cada uno de nuestros pacientes.

Clínica Vida Abrir

The Python dictionary is written to a row in a CSV file.

$ cat [Link]
first_name,last_name
John,Smith
Robert,Brown
Julia,Griffin

This is the output.

Python CSV custom dialect


A custom dialect is created with the csv.register_dialect() method.

custom_dialect.py
#!/usr/bin/python3
import csv

csv.register_dialect("hashes", delimiter="#")

f = open('[Link]', 'w')

with f:

writer = [Link](f, dialect="hashes")


[Link](("pens", 4))
[Link](("plates", 2))
[Link](("bottles", 4))
[Link](("cups", 1))

The program uses a (#) character as a delimiter. The dialect is specified with the dialect option in
the [Link]() method.

$ cat [Link]
pens#4
plates#2
bottles#4
cups#1

This is the output.

In this tutorial, we have worked with CSV in Python.


List all Python tutorials.

Home Facebook Twitter Github Subscribe Privacy


© 2007 - 2021 Jan Bodnar admin(at)[Link]

You might also like