Repository navigation
Expand file tree
/
Copy pathcsvEx2.py
More file actions
49 lines (40 loc) · 1.75 KB
/
Copy pathcsvEx2.py
File metadata and controls
49 lines (40 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# CSV 쓰기
import csv
subjects = ['국어', '영어', '수학']
# 먼저 읽어서 집계
with open('data/scores.csv', 'r', encoding='utf-8') as f:
students = list(csv.DictReader(f))
rows = []
for s in students:
scores = [int(s[sub]) for sub in subjects]
rows.append({
'이름': s['이름'],
'학년': int(s['학년']),
'총점': sum(scores),
'평균': round(sum(scores) / len(scores), 2),
})
print('---------- writer : 리스트를 쓴다 ----------')
# newline='' 을 꼭 주세요. 없으면 윈도우에서 빈 줄이 하나씩 끼어듭니다.
with open('output/summary1.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerow(['이름', '학년', '총점', '평균']) # 헤더
for r in rows:
writer.writerow([r['이름'], r['학년'], r['총점'], r['평균']])
print('summary1.csv 작성 완료')
print('---------- DictWriter : 딕셔너리를 쓴다 ----------')
with open('output/summary2.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['이름', '학년', '총점', '평균'])
writer.writeheader()
writer.writerows(rows) # 한 번에
print('summary2.csv 작성 완료')
print('---------- 결과 확인 ----------')
with open('output/summary2.csv', 'r', encoding='utf-8') as f:
print(f.read())
print('---------- 평균 상위 3명만 따로 ----------')
top3 = sorted(rows, key=lambda r: r['평균'], reverse=True)[:3]
with open('output/top3.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['이름', '학년', '총점', '평균'])
writer.writeheader()
writer.writerows(top3)
for r in top3:
print(f"{r['이름']} {r['평균']}")