Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb498a76

Browse files
committed
Remove old CSV section solutions and add new ones
1 parent9686ac9 commitb498a76

File tree

2 files changed

+57
-33
lines changed

2 files changed

+57
-33
lines changed

‎ch11-file-input-and-output/4-read-and-write-csv-data.py

Lines changed: 0 additions & 33 deletions
This file was deleted.
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# 11.5 Read and Write CSV Data
2+
# Solutions to Exercises
3+
4+
5+
# Exercise 1
6+
importcsv
7+
frompathlibimportPath
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+
withfile_path.open(mode="w",encoding="utf-8")asfile:
18+
writer=csv.writer(file)
19+
writer.writerows(numbers)
20+
21+
22+
# Exercise 2
23+
numbers= []
24+
25+
withfile_path.open(mode="r",encoding="utf-8")asfile:
26+
reader=csv.reader(file)
27+
forrowinreader:
28+
int_row= [int(num)fornuminrow]
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+
withfile_path.open(mode="w",encoding="utf-8")asfile:
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+
withfile_path.open(mode="r",encoding="utf-8")asfile:
53+
reader=csv.DictReader(file)
54+
forrowinreader:
55+
favorite_colors.append(row)
56+
57+
print(favorite_colors)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp