Python csv Module
CSV (Comma-Separated Values) files are a common file format for storing tabular data.
CSV files consist of plain text, where each row represents a row of data in the table, and each column is separated by a comma (or other delimiter).
CSV files are commonly used for data exchange because they are simple and easy to handle.
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
Section titled “1. Reading CSV Files”To read a CSV file, you can use the csv.reader object. Here is a simple example:
Example
Section titled “Example”Code Explanation:
Section titled “Code Explanation:”open('data.csv', mode='r', encoding='utf-8'): Opens the file nameddata.csvin read-only mode, specifying the encoding as UTF-8.csv.reader(file): Creates acsv.readerobject for reading the file content.for row in csv_reader: Reads the file content row by row, with each row of data parsed as a list.
2. Writing CSV Files
Section titled “2. Writing CSV Files”To write a CSV file, you can use the csv.writer object. Here is an example:
Example
Section titled “Example”Code Explanation:
Section titled “Code Explanation:”open('output.csv', mode='w', encoding='utf-8', newline=''): Opens the file namedoutput.csvin write mode, specifying the encoding as UTF-8.newline=''is used to avoid blank lines on Windows systems.csv.writer(file): Creates acsv.writerobject for writing file content.csv_writer.writerow(row): Writes each row of data to the file.
3. Reading and Writing CSV Files Using Dictionaries
Section titled “3. Reading and Writing CSV Files Using Dictionaries”The csv module also provides the DictReader and DictWriter classes, which can parse each row of a CSV file as a dictionary, or write dictionaries to a CSV file.
Reading CSV Files with DictReader:
Section titled “Reading CSV Files with DictReader:”Example
Section titled “Example”Writing CSV Files with DictWriter:
Section titled “Writing CSV Files with DictWriter:”Example
Section titled “Example”Common Attributes and Methods
Section titled “Common Attributes and Methods”Core Methods of the csv Module
Section titled “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 headers) | 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 (e.g., delimiter) | `csv.register_dialect(‘mydialect’, delimiter=’ |
csv.unregister_dialect() |
Unregister 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
Section titled “Common Methods of csv.reader and csv.writer Objects”| Method | Description | Applicable Object |
|---|---|---|
__next__() |
Iteratively read the next row (or use a for loop) |
reader |
writerow(row) |
Write a single row of data | writer |
writerows(rows) |
Write multiple rows of data (list of lists) | writer |
csv.DictReader and csv.DictWriter Object Features
Section titled “csv.DictReader and csv.DictWriter Object Features”| Feature/Method | Description | Example |
|---|---|---|
fieldnames |
List of field names (DictReader auto-obtains from the first row) |
dict_reader.fieldnames |
writeheader() |
Write the header row (DictWriter only) |
dict_writer.writeheader() |
Common Parameter Descriptions
Section titled “Common Parameter Descriptions”| Parameter | Description | Example Value | Applicable Method |
|---|---|---|---|
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 delimiter | True/False |
reader |
lineterminator |
Line terminator | '\r\n' (default) |
writer |
dialect |
Predefined dialect name | 'excel' (default) |
All methods |
Examples
Section titled “Examples”1. Reading a CSV File
Example
Section titled “Example”2. Writing a CSV File
Example
Section titled “Example”3. Using DictReader and DictWriter (with Headers)
Example
Section titled “Example”4. Custom Dialect (e.g., Handling TSV Files)