파이썬에서 다양한 데이터 파일을 읽어오는 코드를 정리한 글로 추후 빠르게 참조하기 위한 목적으로 작성 되었습니다.
CSV 파일 읽기
import csv
rows = []
with open('../data/fileName.csv') as csvfile:
csvreader = csv.reader(csvfile)
next(csvreader, None)
for row in csvreader:
rows.append(row)
3번의 next 함수는 csv 파일의 첫줄에 있는 필드명을 건너뛰기 위함입니다. rows에 데이터가 저장됩니다.
JSON 파일 읽기
import json
with open('../data/fileName.json') as jsonfile:
data = json.load(jsonfile)
value_plainType = data["key1"]
value_arrayType = data["key2"]
value_dictionaryType = data["key3"]
print(value_plainType)
print(value_arrayType)
print(value_dictionaryType["name"])
위의 fileName.json 파일의 내용이 다음과 같을때..
{
"key1" : "string/numeric/bool",
"key2" : [1, 2, 3, 4, 5],
"key3" : { "name":"DoWise", "age": 12 }
}
출력 결과는 다음과 같습니다.
string/numeric/bool [1, 2, 3, 4, 5] DoWise

