15.2. CSV Dump
csv.writer()csv.DictWriter()
15.2.1. SetUp
>>> import csv
15.2.2. Sequence
tuple -> string
open(file, mode='wt', encoding='utf-8')csv.writer(file)writer.writerow(row)
>>> DATA = ('Alice', 'Apricot', 30)
>>>
>>> with open('/tmp/myfile.csv', mode='wt', encoding='utf-8') as file:
... writer = csv.writer(file)
... writer.writerow(DATA)
18
Result:
>>> print(open('/tmp/myfile.csv').read())
Alice,Apricot,30
15.2.3. List of Sequences
list[tuple] -> string
open(file, mode='wt', encoding='utf-8')csv.writer(file)writer.writerows(rows)
>>> DATA = [
... ('firstname', 'lastname', 'age'),
... ('Alice', 'Apricot', 30),
... ('Bob', 'Blackthorn', 31),
... ('Carol', 'Corn', 32),
... ('Dave', 'Durian', 33),
... ('Eve', 'Elderberry', 34),
... ('Mallory', 'Melon', 15),
... ]
>>>
>>> with open('/tmp/myfile.csv', mode='wt', encoding='utf-8') as file:
... writer = csv.writer(file)
... writer.writerows(DATA)
Result:
>>> print(open('/tmp/myfile.csv').read())
firstname,lastname,age
Alice,Apricot,30
Bob,Blackthorn,31
Carol,Corn,32
Dave,Durian,33
Eve,Elderberry,34
Mallory,Melon,15
15.2.4. Mapping
dict -> string
open(file, mode='wt', encoding='utf-8')csv.DictWriter(file, fieldnames)result.writeheader()result.writerow(DATA)
>>> DATA = {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}
>>>
>>>
>>> fieldnames = DATA.keys()
>>>
>>> with open('/tmp/myfile.csv', mode='wt', encoding='utf-8') as file:
... result = csv.DictWriter(file, fieldnames)
... result.writeheader()
... result.writerow(DATA)
24
18
Result:
>>> print(open('/tmp/myfile.csv').read())
firstname,lastname,age
Alice,Apricot,30
15.2.5. List of Mappings
list[dict] -> string
fieldnames = sorted(set(str(key) for row in DATA for key in row.keys()))csv.DictWriter(file, fieldnames)result.writeheader()result.writerows(DATA)
>>> DATA = [
... {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
... {'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31},
... {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
... {'firstname': 'Dave', 'lastname': 'Durian', 'age': 33},
... {'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34},
... {'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15},
... ]
>>>
>>>
>>> fieldnames = sorted(set(str(key) for row in DATA for key in row.keys()))
>>>
>>> with open('/tmp/myfile.csv', mode='wt', encoding='utf-8') as file:
... result = csv.DictWriter(file, fieldnames)
... result.writeheader()
... result.writerows(DATA)
24
Result:
>>> print(open('/tmp/myfile.csv').read())
age,firstname,lastname
30,Alice,Apricot
31,Bob,Blackthorn
32,Carol,Corn
33,Dave,Durian
34,Eve,Elderberry
15,Mallory,Melon
15.2.6. List of Objects
vars(obj)convertsobjtodict
>>> class User:
... def __init__(self, firstname, lastname, age):
... self.firstname = firstname
... self.lastname = lastname
... self.age = age
...
... def __repr__(self):
... clsname = self.__class__.__name__
... firstname = self.firstname
... lastname = self.lastname
... age = self.age
... return f'{clsname}({firstname=}, {lastname=}, {age=})'
>>>
>>>
>>> DATA = [
... User('Alice', 'Apricot', age=30),
... User('Bob', 'Blackthorn', age=31),
... User('Carol', 'Corn', age=32),
... User('Dave', 'Durian', age=33),
... User('Eve', 'Elderberry', age=34),
... User('Mallory', 'Melon', age=15),
... ]
>>>
>>> data = [vars(obj) for obj in DATA]
>>> fieldnames = sorted(set(str(key) for row in data for key in row.keys()))
>>>
>>> with open('/tmp/myfile.csv', mode='wt', encoding='utf-8') as file:
... result = csv.DictWriter(file, fieldnames)
... result.writeheader()
... result.writerows(data)
24
Result:
>>> print(open('/tmp/myfile.csv').read())
age,firstname,lastname
30,Alice,Apricot
31,Bob,Blackthorn
32,Carol,Corn
33,Dave,Durian
34,Eve,Elderberry
15,Mallory,Melon
15.2.7. Assignments
# %% About
# - Name: CSV Writer Sequence
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Using `csv.writer()` save `DATA` to file
# 2. Use Unix `\n` line terminator
# 3. Run doctests - all must succeed
# %% Polish
# 1. Za pomocą `csv.writer()` zapisz `DATA` do pliku
# 2. Użyj zakończenia linii Unix `\n`
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> result
# Alice,Apricot,30
# <BLANKLINE>
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> result = open(FILE).read()
>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is str, \
'Variable `result` has an invalid type; expected: `str`.'
>>> from os import remove
>>> remove(FILE)
>>> print(result)
Alice,Apricot,30
<BLANKLINE>
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
import csv
# %% Types
# %% Data
FILE = r'_temporary.csv'
DATA = ('Alice', 'Apricot', 30)
# %% Result
with open(FILE, mode='wt', encoding='utf-8') as file:
...
# %% About
# - Name: CSV Writer ListSequence
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Using `csv.writer()` save `DATA` to file
# 2. Use Unix `\n` line terminator
# 3. Run doctests - all must succeed
# %% Polish
# 1. Za pomocą `csv.writer()` zapisz `DATA` do pliku
# 2. Użyj zakończenia linii Unix `\n`
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> result
# firstname,lastname,age
# Alice,Apricot,30
# Bob,Blackthorn,31
# Carol,Corn,32
# Dave,Durian,33
# Eve,Elderberry,34
# Mallory,Melon,15
# <BLANKLINE>
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> result = open(FILE).read()
>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is str, \
'Variable `result` has an invalid type; expected: `str`.'
>>> from os import remove
>>> remove(FILE)
>>> print(result)
firstname,lastname,age
Alice,Apricot,30
Bob,Blackthorn,31
Carol,Corn,32
Dave,Durian,33
Eve,Elderberry,34
Mallory,Melon,15
<BLANKLINE>
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
import csv
# %% Types
# %% Data
FILE = r'_temporary.csv'
DATA = [
('firstname', 'lastname', 'age'),
('Alice', 'Apricot', 30),
('Bob', 'Blackthorn', 31),
('Carol', 'Corn', 32),
('Dave', 'Durian', 33),
('Eve', 'Elderberry', 34),
('Mallory', 'Melon', 15),
]
# %% Result
with open(FILE, mode='wt', encoding='utf-8') as file:
...
# %% About
# - Name: CSV DictWriter Mapping
# - Difficulty: easy
# - Lines: 5
# - Minutes: 3
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Write `DATA` to `FILE` in CSV format
# 2. Use `csv.DictWriter()`
# 3. Sort header (fieldnames)
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zapisz `DATA` do `FILE` w formacie CSV
# 2. Użyj `csv.DictWriter()`
# 3. Posortuj nagłówek (fieldnames)
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> result
# firstname,lastname,age
# Alice,Apricot,30
# <BLANKLINE>
# %% Hints
# - `sorted()`
# - `dict.keys()`
# - `csv.DictWriter()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> result = open(FILE).read()
>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is str, \
'Variable `result` has an invalid type; expected: `str`.'
>>> from os import remove
>>> remove(FILE)
>>> print(result)
firstname,lastname,age
Alice,Apricot,30
<BLANKLINE>
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
import csv
# %% Types
# %% Data
FILE = r'_temporary.csv'
DATA = {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}
# %% Result
with open(FILE, mode='wt', encoding='utf-8') as file:
...
# %% About
# - Name: CSV DictWriter ListMappings
# - Difficulty: easy
# - Lines: 5
# - Minutes: 3
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Write `DATA` to `FILE` in CSV format
# 2. Use `csv.DictWriter()`
# 3. Sort header (fieldnames)
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zapisz `DATA` do `FILE` w formacie CSV
# 2. Użyj `csv.DictWriter()`
# 3. Posortuj nagłówek (fieldnames)
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> result
# age,firstname,lastname
# 30,Alice,Apricot
# 31,Bob,Blackthorn
# 32,Carol,Corn
# 33,Dave,Durian
# 34,Eve,Elderberry
# 15,Mallory,Melon
# <BLANKLINE>
# %% Hints
# - `sorted()`
# - `dict.keys()`
# - `csv.DictWriter()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> result = open(FILE).read()
>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is str, \
'Variable `result` has an invalid type; expected: `str`.'
>>> from os import remove
>>> remove(FILE)
>>> print(result)
age,firstname,lastname
30,Alice,Apricot
31,Bob,Blackthorn
32,Carol,Corn
33,Dave,Durian
34,Eve,Elderberry
15,Mallory,Melon
<BLANKLINE>
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
import csv
# %% Types
# %% Data
FILE = r'_temporary.csv'
DATA = [
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
{'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31},
{'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
{'firstname': 'Dave', 'lastname': 'Durian', 'age': 33},
{'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34},
{'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15},
]
# %% Result
with open(FILE, mode='wt', encoding='utf-8') as file:
...
# %% About
# - Name: CSV DictWriter ListObjects
# - Difficulty: easy
# - Lines: 6
# - Minutes: 3
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Write `DATA` to `FILE` in CSV format
# 2. Use `csv.DictWriter()`
# 3. Sort header (fieldnames)
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zapisz `DATA` do `FILE` w formacie CSV
# 2. Użyj `csv.DictWriter()`
# 3. Posortuj nagłówek (fieldnames)
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> result
# age,firstname,lastname
# 30,Alice,Apricot
# 31,Bob,Blackthorn
# 32,Carol,Corn
# 33,Dave,Durian
# 34,Eve,Elderberry
# 15,Mallory,Melon
# <BLANKLINE>
# %% Hints
# - `vars()`
# - `sorted()`
# - `dict.keys()`
# - `csv.DictWriter()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> result = open(FILE).read()
>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is str, \
'Variable `result` has an invalid type; expected: `str`.'
>>> from os import remove
>>> remove(FILE)
>>> print(result)
age,firstname,lastname
30,Alice,Apricot
31,Bob,Blackthorn
32,Carol,Corn
33,Dave,Durian
34,Eve,Elderberry
15,Mallory,Melon
<BLANKLINE>
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
import csv
# %% Types
# %% Data
FILE = r'_temporary.csv'
class User:
def __init__(self, firstname, lastname, age=None):
self.firstname = firstname
self.lastname = lastname
self.age = age
def __repr__(self):
clsname = self.__class__.__qualname__
arguments = ', '.join(f'{k}={v!r}' for k,v in vars(self).items())
return f'{clsname}({arguments})'
DATA = [
User('Alice', 'Apricot', age=30),
User('Bob', 'Blackthorn', age=31),
User('Carol', 'Corn', age=32),
User('Dave', 'Durian', age=33),
User('Eve', 'Elderberry', age=34),
User('Mallory', 'Melon', age=15),
]
# %% Result
with open(FILE, mode='wt', encoding='utf-8') as file:
...