YouTip LogoYouTip

Python Csv

Python3.x Python csv Module

CSV (Comma-Separated Values) files are a common file format used to store tabular data.

CSV files consist of plain text, where each line represents a row of data in a table, and each column is separated by commas (or other delimiters).

CSV files are commonly 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 the process of handling CSV files, allowing developers to easily manipulate tabular data.


1. Reading CSV Files

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

Example

import csv

# Open CSV file

with open('data.csv', mode='r', encoding='utf-8')as file:

# Create csv.reader object

 csv_reader =csv.reader(file)

# Read data line by line

for row in csv_reader:

print(row)
Code Explanation:
  • open('data.csv', mode='r', encoding='utf-8'): Opens the file named data.csv in read-only mode and specifies the encoding as UTF-8.
  • csv.reader(file): Creates a csv.reader object to read the file contents.
  • for row in csv_reader: Reads the file contents line by line, with each row of data parsed into a list.

2. Writing CSV Files

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

Example

import csv

# Data to be written

 data =[

['Name','Age','City'],

['Alice','30','New York'],

['Bob','25','Los Angeles']

]

# Open CSV file

with open('output.csv', mode='w', encoding='utf-8', newline='')as file:

# Create csv.writer object

 csv_writer =csv.writer(file)

# Write data

for row in data:

 csv_writer.writerow(row)
Code Explanation:
  • open('output.csv', mode='w', encoding='utf-8', newline=''): Opens the file named output.csv in write mode and specifies the encoding as UTF-8. newline='' is used to prevent blank lines on Windows systems.
  • csv.writer(file): Creates a csv.writer object to write to the file contents.
  • csv_writer.writerow(row): Writes each row of data to the file.

3. Reading and Writing CSV Files Using Dictionaries

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

Reading CSV Files with DictReader:

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)

Writing CSV Files with DictWriter:

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 header

 csv_dict_writer.writeheader()

# Write data

for row in data:

 csv_dict_writer.writerow(row)

Common Attributes and Methods

Core Methods of the csv Module

MethodDescriptionExample
csv.reader()Reads CSV data from a file objectreader = csv.reader(file)
csv.writer()Writes data to a CSV filewriter = csv.writer(file)
csv.DictReader()Reads CSV rows as dictionaries (with header)dict_reader = csv.DictReader(file)
csv.DictWriter()Writes dictionaries to a CSV file (requires fieldnames)dict_writer = csv.DictWriter(file, fieldnames)
csv.register_dialect()Registers a custom CSV dialect (e.g., delimiter)csv.register_dialect('mydialect', delimiter='|')
csv.unregister_dialect()Removes a registered dialectcsv.unregister_dialect('mydialect')
csv.list_dialects()Lists all registered dialectsprint(csv.list_dialects())

Common Methods for csv.reader and csv.writer Objects

MethodDescriptionApplicable Object
__next__()Iterates to the next row (or use for loop)reader
writerow(row)Writes a single row of datawriter
writerows(rows)Writes multiple rows of data (list of lists)writer

Features of csv.DictReader and csv.DictWriter Objects

Feature/MethodDescriptionExample
fieldnamesList of field names (DictReader automatically gets it from the first row)dict_reader.fieldnames
writeheader()Writes the header row (specific to DictWriter)dict_writer.writeheader()

Common Parameter Descriptions

ParameterDescriptionExample ValueApplicable Method
delimiterField delimiter',' (default), '\t'reader/writer
quotecharQuote character (encloses special fields)'"' (default)reader/writer
quotingQuoting rulecsv.QUOTE_ALL (quote all)reader/writer
skipinitialspaceIgnore spaces after delimiterTrue/Falsereader
lineterminatorLine terminator'\r\n' (default)writer
dialectPredefined dialect name'excel' (default)All methods

Examples

  1. Reading a 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. Writing a 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. Using DictReader and DictWriter (with headers)

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 via 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 header

 dict_writer.writerow({'Name': 'Alice','Age': 25})
  1. Custom Dialect (e.g., processing 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)
← Python AsyncioPython Datetime β†’