8000 Update 6-read-and-write-csv-data.py · NamLQ/python-basics-exercises@e4568cb · GitHub
[go: up one dir, main page]

Skip to content

Commit e4568cb

Browse files
authored
Update 6-read-and-write-csv-data.py
Changed the key from 'favorite_color' to 'favorite color' and vice versa as required in exercises 3 and 4.
1 parent 9d61225 commit e4568cb

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

ch12-file-input-and-output/6-read-and-write-csv-data.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,18 +40,31 @@
4040

4141
file_path = Path.home() / "favorite_colors.csv"
4242

43-
with file_path.open(mode="w", encoding="utf-8") as file:
44-
writer = csv.DictWriter(file, fieldnames=["name", "favorite_color"])
43+
def change_key(color, old_key, new_key):
44+
value = color[old_key]
45+
del color[old_key]
46+
color[new_key] = value
47+
return color
48+
49+
favorite_colors =[change_key(color, 'favorite_color', 'favorite color')
50+
for color in favorite_colors]
51+
52+
with file_path.open('w', encoding = 'utf-8') as file:
53+
writer = csv.DictWriter(file, favorite_colors[0].keys())
4554
writer.writeheader()
4655
writer.writerows(favorite_colors)
4756

48-
4957
# Exercise 4
5058
favorite_colors = []
5159

52-
with file_path.open(mode="r", encoding="utf-8") as file:
53-
reader = csv.DictReader(file)
60+
with file_path.open('r', encoding = 'utf-8') as file:
61+
header = file.readline()
62+
header = header.replace('\n', '')
63+
header = header.split(',')
64+
65+
reader = csv.DictReader(file, fieldnames = header)
5466
for row in reader:
67+
row = change_key(row, 'favorite color', 'favorite_color')
5568
favorite_colors.append(row)
5669

5770
print(favorite_colors)

0 commit comments

Comments
 (0)
0