python 외부 파일 처리 - Excel, CSV 읽기 쓰기

2020. 4. 18. 08:53python

 CSV : MIME - text/csv

 

CSV 읽기

import csv

#1. ,로 구분되어 있을 
with open('./resource/sample/csv', 'r') as f:
	reader = csv.reader(f)
    
    next(reader) #passing, Header  스킵
    for c in reader:
    	print(c)
        
        
        
#2. |로 구분되어 있을 때
with open('./resource/sample/csv', 'r') as f:
	reader = csv.reader(f, deliniter = '|') # 이 파일은 |으로 구분되어 있다, | 없애줌
    
    next(reader) #passing, Header  스킵
    for c in reader:
    	print(c)
        
        
#3. Dict 변환
with open('./resource/sample/csv', 'r') as f:
	reader = csv.DictReader(f) #딕셔너리 형태로 받아오기
    
    for c i n reader:
    	for k, v in c.items(): # 디셔너리 처럼 출력, 이름 정순미, 가입일시 2017, 나이 33 
        	print(k,v)
        print('--------------')

CSV 쓰기

w = [[1,2,3],[4,5,6],[7,8,9]]
 # 1.
with open('./resource/sample3.csv', 'w', newline = '') as f: #newline = '' -> 띄어쓰기 한번만
	wt = csv.writer(f)
    
    for v in w:
    	wt.writernow(v)
        
        
# ->  1, 2, 3
# ->  4, 5, 6
# ->  7, 8, 9        
# 2.
with open('./resource/sample3.csv', 'w', newline = '') as f:
	wt = csv.writer(f)
    wt.writerows(w) #리스트를 한번에 쓰게함.

XSL, XLSX 읽기

pandas 를 주로 사용(openpyx1, x1rd)

설치방법

pip install xlrd

pip install openpyxl

pip install pandas


import pandas as pd
xlsx = pd.read_excel('./resource/sample.xlsx')
# 상위 데이터 확인
 print(xlxs.head()) #위에서부터 5개만 출력

# 데이터 확인
print(xlxs.tail()) #아래에서부터 5개만 출력

# 데이터 확인
print(xlxs.shpae) #행, 열 출력 # -> (20, 7)

# sheetname = '시트명' 또는 숫자, header=숫자(몇번째 행부터), skiprow=숫자(행 생략)
xlsx = pd.read_excel('./resource/sample.xlsx', skiprow)

XSL, XLSX, CSV 쓰기

xlsx.to_excel('./resource/result.xlsx', index=False)
xlsx.to_csv('./resource/result.csv', index=False)