File tree 1 file changed +18
-5
lines changed
ch12-file-input-and-output 1 file changed +18
-5
lines changed Original file line number Diff line number Diff line change 40
40
41
41
file_path = Path .home () / "favorite_colors.csv"
42
42
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 ())
45
54
writer .writeheader ()
46
55
writer .writerows (favorite_colors )
47
56
48
-
49
57
# Exercise 4
50
58
favorite_colors = []
51
59
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 )
54
66
for row in reader :
67
+ row = change_key (row , 'favorite color' , 'favorite_color' )
55
68
favorite_colors .append (row )
56
69
57
70
print (favorite_colors )
You can’t perform that action at this time.
0 commit comments