17.2. CSV Writer
Writes iterable of iterables (eg. list[list], list[tuple]) to CSV file
csv.writer()
Remember to add
mode='w'
toopen()
functionDefault encoding is
encoding='utf-8'
17.2.1. SetUp
>>> import csv
17.2.2. Minimal
>>> DATA = [
... ('Mark', 'Watney', 40),
... ('Melissa', 'Lewis', 41),
... ('Rick', 'Martinez', 39),
... ]
>>>
>>> with open('/tmp/myfile.csv', mode='wt') as file:
... writer = csv.writer(file)
... writer.writerows(DATA)
Result:
>>> print(open('/tmp/myfile.csv').read())
Mark,Watney,40
Melissa,Lewis,41
Rick,Martinez,39
17.2.3. Parametrized
>>> DATA = [
... ('Mark', 'Watney', 40),
... ('Melissa', 'Lewis', 41),
... ('Rick', 'Martinez', 39),
... ]
>>>
>>> with open('/tmp/myfile.csv', mode='wt', encoding='utf-8') as file:
... writer = csv.writer(file, delimiter=',', quoting=csv.QUOTE_ALL, quotechar='"', lineterminator='\n')
... writer.writerows(DATA)
Result:
>>> print(open('/tmp/myfile.csv').read())
"Mark","Watney","40"
"Melissa","Lewis","41"
"Rick","Martinez","39"
17.2.4. Assignments
# %% 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
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: CSV Writer Iris
# - Difficulty: easy
# - Lines: 3
# - Minutes: 5
# %% 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ść
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> result = open(FILE).read()
>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> from os import remove
>>> remove(FILE)
>>> print(result)
firstname,lastname,age
Mark,Watney,42
Melissa,Lewis,41
Rick,Martinez,40
Alex,Vogel,42
Beth,Johanssen,29
Chris,Beck,36
<BLANKLINE>
"""
import csv
FILE = r'_temporary.csv'
DATA = [
('firstname', 'lastname', 'age'),
('Mark', 'Watney', 42),
('Melissa', 'Lewis', 41),
('Rick', 'Martinez', 40),
('Alex', 'Vogel', 42),
('Beth', 'Johanssen', 29),
('Chris', 'Beck', 36),
]
# Using `csv.writer()` save `DATA` to file
# Use Unix `\n` line terminator
# type: ContextManager
with open(FILE, mode='wt', encoding='utf-8') as file:
...
# %% 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
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: CSV Writer Iris
# - Difficulty: easy
# - Lines: 3
# - Minutes: 5
# %% 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ść
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> result = open(FILE).read()
>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> from os import remove
>>> remove(FILE)
>>> print(result)
firstname,lastname,age
Mark,Watney,42
Melissa,Lewis,41
Rick,Martinez,40
Alex,Vogel,42
Beth,Johanssen,29
Chris,Beck,36
<BLANKLINE>
"""
import csv
FILE = r'_temporary.csv'
DATA = [
{'firstname': 'Mark', 'lastname': 'Watney', 'age': 42},
{'firstname': 'Melissa', 'lastname': 'Lewis', 'age': 41},
{'firstname': 'Rick', 'lastname': 'Martinez', 'age': 40},
{'firstname': 'Alex', 'lastname': 'Vogel', 'age': 42},
{'firstname': 'Beth', 'lastname': 'Johanssen', 'age': 29},
{'firstname': 'Chris', 'lastname': 'Beck', 'age': 36},
]
# Using `csv.writer()` save `DATA` to file
# Use Unix `\n` line terminator
# type: ContextManager
with open(FILE, mode='wt', encoding='utf-8') as file:
...
# %% 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
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: CSV Writer Iris
# - Difficulty: easy
# - Lines: 3
# - Minutes: 5
# %% 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ść
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> result = open(FILE).read()
>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> from os import remove
>>> remove(FILE)
>>> print(result)
firstname,lastname,age
Mark,Watney,40
Melissa,Lewis,41
Rick,Martinez,39
Alex,Vogel,42
Beth,Johanssen,29
Chris,Beck,36
<BLANKLINE>
"""
import csv
FILE = r'_temporary.csv'
class User:
def __init__(self, firstname, lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age = age
DATA = [
User('Mark', 'Watney', age=40),
User('Melissa', 'Lewis', age=41),
User('Rick', 'Martinez', age=39),
User('Alex', 'Vogel', age=42),
User('Beth', 'Johanssen', age=29),
User('Chris', 'Beck', age=36),
]
# Using `csv.writer()` save `DATA` to file
# Use Unix `\n` line terminator
# type: ContextManager
with open(FILE, mode='wt', encoding='utf-8') as file:
...