-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsection11.py
95 lines (73 loc) · 2.14 KB
/
section11.py
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# Section11
# 파이썬 예외처리의 이해
# 파이썬 Excel, CSV 파일 읽기 및 쓰기
# CSV : MIME - text/csv
import csv
# 예제1
with open('./resource/sample1.csv', 'r') as f:
reader = csv.reader(f)
# next(reader) Header 스킵
# 확인
print(reader)
print(type(reader))
print(dir(reader)) # __iter__ 확인
print()
for c in reader:
print(c)
# 예제2
with open('./resource/sample2.csv', 'r') as f:
reader = csv.reader(f, delimiter='|') # 구분자 선택
# next(reader) Header 스킵
# 확인
print(reader)
print(type(reader))
print(dir(reader)) # __iter__ 확인
print()
for c in reader:
print(c)
# 예제3 (Dict 변환)
with open('./resource/sample1.csv', 'r') as f:
reader = csv.DictReader(f)
# 확인
print(reader)
print(type(reader))
print(dir(reader)) # __iter__ 확인
print()
for c in reader:
for k, v in c.items():
print(k, v)
print('-----')
# 예제4
w = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]
with open('./resource/sample3.csv', 'w') as f: # newline='' 테스트
wt = csv.writer(f)
# dir 확인
print(dir(wt))
print(type(wt))
for v in w:
wt.writerow(v)
# 예제5
with open('./resource/sample3.csv', 'w', newline='') as f:
wt = csv.writer(f)
# dir 확인
print(dir(wt))
print(type(wt))
wt.writerows(w)
# XSL, XLSX : MIME - applications/vnd.excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
# pip install pandas 설치 필요
# pip install xlrd 설치 필요
# pip install openpyxl 설치 필요
# openpyxl, xlsxwriter, xlrd, xlwt, xlutils 등 있으나 pandas를 주로 사용(openpyxl, xlrd) 포함
import pandas as pd
xlsx = pd.read_excel('./resource/sample.xlsx') # sheetname='시트명' 또는 숫자, header=3, skiprow=1 실습
# 상위 데이터 확인
print(xlsx.head())
print()
# 데이터 확인
print(xlsx.tail())
print()
# 데이터 구조
print(xlsx.shape) # 행, 열
# 엑셀 or CSV 다시 쓰기
xlsx.to_excel('./resource/result.xlsx', index=False)
xlsx.to_csv('./resource/result.csv', index=False)