파이썬
1. csv 모듈
1-1. 함수 설명 및 파일 읽고 데이터로 저장하기
파일변수 = open('파일경로', encoding='')
DataFrame변수 = csv.reader() : csv파일을 읽어 데이터를 한줄씩 반환
DataFrame변수 = csv.writer() : csv파일에 데이터를 쓰고 저장, 기존 동일 파일명이 있다면 덮어씌움(주의!)
delimiter='' : 괄호를 기준으로 읽기 _ csv파일은 쉼표와 tab 두가지로 구분 표시
r : 읽기 전용
변수.close() : 닫기
# 모듈 import
import csv
#변수에 저장해 파일 열고, 변수에 저장해 파일 읽기
f = open('./data/seoul.csv', 'r', encoding='cp949')
data = csv.reader(f, delimiter=',') #이 상태로는 객체이기 때문에 데이터를 읽을 수 없음
print(data)
f.close() #항상 닫기를 넣어 줘야 함
#for반복문을 이용해 전체 행을 읽기
f = open('./data/seoul.csv', 'r', encoding='cp949')
data = csv.reader(f, delimiter=',')
for row in data :
print(row)
f.close()
#읽어낸 전체 행을 데이터 변수 선언 후, .append해 데이터로 저장
f = open('./data/seoul.csv', 'r', encoding='cp949')
data = csv.reader(f, delimiter=',') #reader(): 한줄씩 1차원 list로 읽어냄
seoul_list = [] #한줄씩 읽어낸 list를 2차원 list로 생성
for row in data :
seoul_list.append(row)
print(row)
f.close()
1-2. header 건너뛰고, 파일 읽고 데이터로 저장하기
next() : 한개의 행을 건너뜀
f = open('./data/seoul.csv', 'r', encoding='cp949')
data = csv.reader(f)
header = next(data)
print(header)
f.close()
f = open('./data/seoul.csv', 'r', encoding='cp949')
data = csv.reader(f)
header = next(data)
seoul_list_noheader = []
for row in data :
seoul_list_noheader.append(row)
print(header)
f.close()