|
| 1 | +# 11.5 Read and Write CSV Data |
| 2 | +# Solutions to Exercises |
| 3 | + |
| 4 | + |
| 5 | +# Exercise 1 |
| 6 | +import csv |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +numbers = [ |
| 10 | + [1, 2, 3, 4, 5], |
| 11 | + [6, 7, 8, 9, 10], |
| 12 | + [11, 12, 13, 14, 15], |
| 13 | +] |
| 14 | + |
| 15 | +file_path = Path.home() / "numbers.csv" |
| 16 | + |
| 17 | +with file_path.open(mode="w", encoding="utf-8") as file: |
| 18 | + writer = csv.writer(file) |
| 19 | + writer.writerows(numbers) |
| 20 | + |
| 21 | + |
| 22 | +# Exercise 2 |
| 23 | +numbers = [] |
| 24 | + |
| 25 | +with file_path.open(mode="r", encoding="utf-8") as file: |
| 26 | + reader = csv.reader(file) |
| 27 | + for row in reader: |
| 28 | + int_row = [int(num) for num in row] |
| 29 | + numbers.append(int_row) |
| 30 | + |
| 31 | +print(numbers) |
| 32 | + |
| 33 | + |
| 34 | +# Exercise 3 |
| 35 | +favorite_colors = [ |
| 36 | + {"name": "Joe", "favorite_color": "blue"}, |
| 37 | + {"name": "Anne", "favorite_color": "green"}, |
| 38 | + {"name": "Bailey", "favorite_color": "red"}, |
| 39 | +] |
| 40 | + |
| 41 | +file_path = Path.home() / "favorite_colors.csv" |
| 42 | + |
| 43 | +with file_path.open(mode="w", encoding="utf-8") as file: |
| 44 | + writer = csv.DictWriter(file, fieldnames=["name", "favorite_color"]) |
| 45 | + writer.writeheader() |
| 46 | + writer.writerows(favorite_colors) |
| 47 | + |
| 48 | + |
| 49 | +# Exercise 4 |
| 50 | +favorite_colors = [] |
| 51 | + |
| 52 | +with file_path.open(mode="r", encoding="utf-8") as file: |
| 53 | + reader = csv.DictReader(file) |
| 54 | + for row in reader: |
| 55 | + favorite_colors.append(row) |
| 56 | + |
| 57 | +print(favorite_colors) |
0 commit comments