Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python csv Module

Python csv Module

A CSV (Comma-Separated Values) file is a common file format for storing tabular data.

A CSV file consists of plain text; each line represents a row of data in the table, and columns are separated by commas (or another delimiter).

CSV files are usually used for data exchange because they are simple and easy to process.

Python provides a built-in csv module for reading and writing CSV files. This module simplifies working with CSV files, letting developers handle tabular data easily.


1. Reading a CSV file

To read a CSV file, you can use the csv.reader object. Here is a simple example:

Example

import

csv

Open the CSV file

with

open

(

'data.csv'

,

mode

=

'r'

,

encoding

=

'utf-8'

)

as

file

:

   

Create a csv.reader object

    csv_reader

=

csv

.

reader

(

file

)

   

   

Read the data line by line

   

for

row

in

csv_reader:

       

print

(

row

)

Code Explanation:


2. Writing a CSV file

To write a CSV file, you can use the csv.writer object. Here is an example:

Example

import

csv

The data to write

data

=

[

   

[

'Name'

,

'Age'

,

'City'

]

,

   

[

'Alice'

,

'30'

,

'New York'

]

,

   

[

'Bob'

,

'25'

,

'Los Angeles'

]

]

Open the CSV file

with

open

(

'output.csv'

,

mode

=

'w'

,

encoding

=

'utf-8'

,

newline

=

''

)

as

file

:

   

Create a csv.writer object

    csv_writer

=

csv

.

writer

(

file

)

   

   

Write the data

   

for

row

in

data:

        csv_writer.

writerow

(

row

)

Code Explanation:


3. Reading and writing CSV files with dictionaries

csv The module also provides the DictReader and DictWriter classes, which parse each line of a CSV file into a dictionary or write dictionaries to a CSV file.

Use DictReader Reading a CSV file:

Example

import

csv

with

open

(

'data.csv'

,

mode

=

'r'

,

encoding

=

'utf-8'

)

as

file

:

    csv_dict_reader

=

csv

.

DictReader

(

file

)

   

   

for

row

in

csv_dict_reader:

       

print

(

row

)

Use DictWriter Writing a CSV file:

Example

import

csv

data

=

[

   

{

'Name'

:

'Alice'

,

'Age'

:

'30'

,

'City'

:

'New York'

}

,

   

{

'Name'

:

'Bob'

,

'Age'

:

'25'

,

'City'

:

'Los Angeles'

}

]

with

open

(

'output.csv'

,

mode

=

'w'

,

encoding

=

'utf-8'

,

newline

=

''

)

as

file

:

    fieldnames

=

[

'Name'

,

'Age'

,

'City'

]

    csv_dict_writer

=

csv

.

DictWriter

(

file

,

fieldnames

=

fieldnames

)

   

   

Write the header row

    csv_dict_writer.

writeheader

(

)

   

   

Write the data

   

for

row

in

data:

        csv_dict_writer.

writerow

(

row

)


Common attributes and methods

Core methods of the csv module

Method Description Example
csv.reader() Read CSV data from a file object reader = csv.reader(file)
csv.writer() Write data to a CSV file writer = csv.writer(file)
csv.DictReader() Read CSV rows as dictionaries (with header) dict_reader = csv.DictReader(file)
csv.DictWriter() Write dictionaries to a CSV file (field names required) dict_writer = csv.DictWriter(file, fieldnames)
csv.register_dialect() Register a custom CSV format (such as a delimiter) csv.register_dialect('mydialect', delimiter='\|')
csv.unregister_dialect() Remove a registered dialect csv.unregister_dialect('mydialect')
csv.list_dialects() List all registered dialects print(csv.list_dialects())

Common methods of csv.reader and csv.writer objects

Method Description Applies to
__next__() Iterate to read the next row (or use a for loop) reader
writerow(row) Write a single row writer
writerows(rows) Write multiple rows (a list of lists) writer

Features of csv.DictReader and csv.DictWriter objects

Feature/method Description Example
fieldnames List of field names (DictReader automatically obtained from the first row) dict_reader.fieldnames
writeheader() Write the header row (DictWriter only) dict_writer.writeheader()

Common parameters

Parameters Description Example value Applicable methods
delimiter Field delimiter ','(default), '\t' reader/writer
quotechar Quote character (wraps special fields) '"'(default) reader/writer
quoting Quoting rule csv.QUOTE_ALL(quote all) reader/writer
skipinitialspace Ignore spaces after the delimiter True/False reader
lineterminator : Make sure to use the correct character set, otherwise it may cause garbled text '\r\n'(default) writer
dialect Predefined dialect name 'excel'(default) All methods

Example

  1. Read the CSV file

Example

import

csv

with

open

(

'data.csv'

,

'r'

)

as

file

:

    reader

=

csv

.

reader

(

file

,

delimiter

=

','

)

   

for

row

in

reader:

       

print

(

row

)

 

Each row is a list

  1. Write the CSV file

Example

data

=

[

[

'Name'

,

'Age'

]

,

[

'Alice'

,

25

]

,

[

'Bob'

,

30

]

]

with

open

(

'output.csv'

,

'w'

,

newline

=

''

)

as

file

:

    writer

=

csv

.

writer

(

file

)

    writer.

writerows

(

data

)

 

Write multiple rows

  1. Use DictReader and DictWriter (with header)

Example

Read

with

open

(

'data.csv'

,

'r'

)

as

file

:

    dict_reader

=

csv

.

DictReader

(

file

)

   

for

row

in

dict_reader:

       

print

(

row

[

'Name'

]

,

row

[

'Age'

]

)

 

Access by field name

Write

fieldnames

=

[

'Name'

,

'Age'

]

with

open

(

'output.csv'

,

'w'

,

newline

=

''

)

as

file

:

    dict_writer

=

csv

.

DictWriter

(

file

,

fieldnames

=

fieldnames

)

    dict_writer.

writeheader

(

)

 

Write the header row

    dict_writer.

writerow

(

{

'Name'

:

'Alice'

,

'Age'

:

25

}

)

  1. Custom dialect (e.g. handling TSV files)

Example

csv

.

register_dialect

(

'tsv'

,

delimiter

=

'\t'

,

quoting

=

csv

.

QUOTE_NONE

)

with

open

(

'data.tsv'

,

'r'

)

as

file

:

    reader

=

csv

.

reader

(

file

,

dialect

=

'tsv'

)

   

for

row

in

reader:

       

print

(

row

)