Python and CSV files - Formula Sheet
Core CSV Methods and Parameters
This reference sheet outlines the built-in syntax, parameters, and dialects of Python's csv module.
1. Opening Files
f = open(file, mode, newline)
- file: The path string pointing to the file.
- mode: The mode parameter, such as read text (
'r'), write text ('w'), append ('a'), or binary ('b'). - newline: Controls line break translation; setting
newline=''prevents empty rows when writing CSVs.
2. CSV Reader Syntax
reader = csv.reader(fileobject, delimiter, fmtparams)
- fileobject: The file handler object returned by the open function.
- delimiter: The column separator character (default is a comma
','). - fmtparams: Dialect formatting parameters such as
skipinitialspace=Trueto trim leading white space.
3. CSV Writer Syntax
writer = csv.writer(fileobject, delimiter, fmtparams)
- fileobject: The open file handle in write or append mode.
- delimiter: The field separator character.
- fmtparams: Dialect format parameters (e.g.,
quoting=csv.QUOTE_ALLto wrap all fields in quotes).
4. Writing Rows
writer.writerow(row) and writer.writerows(rows)
- row: A 1D sequence (list or tuple) representing field values of a single record.
- rows: A 2D sequence containing multiple nested rows to write sequentially.
5. Dictionary Reader and Writer
d_reader = csv.DictReader(fileobject, fieldnames=None) and d_writer = csv.DictWriter(fileobject, fieldnames)
- fieldnames: A sequence of strings that serve as the dictionary keys for row mappings.
- d_writer.writeheader(): Writes a row using the defined fieldnames as headers.
6. Skipping Rows
next(reader)
- reader: The active CSV reader iterator. Moves the cursor to the next line (commonly used to skip header rows).
More for this chapter
Book Back Questions10 textbook MCQs · solved
Additional MCQs15 extra MCQs · solved
Practice TestInteractive · instant score
Book Back TestTest yourself on the textbook set
Additional MCQ TestTest yourself on the extra set
Study NotesConcepts & methods
More chapters in Computer Science
View all
1 Function
2 Data Abstraction
3 Scoping
4 Algorithmic Strategies
5 Python -Variables and Operators
6 Control Structures
7 Python functions
8 Strings and String manipulation
9 Lists, Tuples, Sets and Dictionary
10 Python Classes and objects
11 Database Concepts
12 Structured Query Language (SQL)
14 Importing C++ programs in Python.
15 Data manipulation through SQL
16 Data visualization using pyplot: line chart, pie chart and bar chart