코딩 공부/Python

[Python] json, jsonl 파일 읽고 쓰기

3월의 눈사람 2025. 4. 21. 10:59

json 파일 읽기

import json

with open("sample_file.json", "r", encoding='UTF-8') as json_file:
    json_data = json.load(json_file)
  • with open의 encoding 옵션은 없어도 되는 값
    • encoding은 말 그대로 문자 encoding 방식
    • default는 windows의 경우 보통 'cp1252' 또는 'mbcs' ('cp949'와 유사한 애들), mac이나 linux의 경우 'UTF-8'
encoding 설명
utf-8 국제 표준. 거의 대부분에서 사용됨
utf-8-sig Byte Order Mark (BOM)이 포함된 UTF-8 (엑셀/윈도우 호환성)
cp949 윈도우 한국어 기본 인코딩 (한글이 깨지는 원인으로 빈번하게 등장)
euc-kr 옛날 한국어 웹사이트에서 사용되던 인코딩
latin-1 유럽권 기본 인코딩

 

json 파일 쓰기

import json

with open("sample_file.json", "w", encoding="UTF-8") as json_file:
    json.dump(target_data, json_file, ensure_ascii=False, indent=4, sort_keys=True)
  • json.dump의 ensure_ascii, indent, sort_key과 with open의 encoding 옵션은 없어도 되는 값들 
    • ensure_ascii는 ascii code로 쓰는 옵션. 한글로 저장하고 싶다면 False로 조정해 줘야 함 
    • indent는 json 파일을 쓸 때 가독성이 좋도록 들여쓰기 및 줄바꿈 정리.  4가 일반적으로 많이 쓰임
    • sort_keys는 dict 형식의 data (예시의 target_data)를 key를 기준으로 정렬해 작성하도록 하는 옵션
    • 만약 value로 정렬하고 싶다면 아래를 추가하고 target_data를 sorted_data로 바꿔주면 됨
from collections import OrderedDict

sorted_data = OrderedDict(sorted(target_data.items(), key=lambda item: item[1]))
  • with open의 mode 종류
mode 설명
'r' 읽기(read) 파일이 있어야 함. 없으면 FileNotFoundError
'w' 쓰기(write) 파일 새로 생성 또는 기존 파일 내용 삭제 후 새로 씀
'a' 이어쓰기(append) 파일 끝에 내용을 추가. 파일 없으면 새로 생성
'x' 배타적 생성(eXclusive) 파일이 없을 때만 생성. 이미 있으면 에러
'b' 이진(binary) 텍스트가 아닌 이진 데이터 (예: 이미지, 오디오 등) 처리용
't' 텍스트(text) (기본값) 텍스트 파일 처리
'+' 읽기 + 쓰기 기존 파일에 대해 읽고 쓰기 모두 가능

 

jsonl 파일 읽기

  • jsonl파일은 json이 여러개 (dict가 여러개) 있는 파일이라고 생각하면 된다
import jsonlines

jsonl_data = []
with jsonlines.open("sample_file.jsonl") as jsonl_file:
    for line in jsonl_file.iter():
    	jsonl_data.append(line)
  • 이렇게 하면 jsonl_data라는 list의 각각의 값들이 json 형식 (dict)의 값들이 된다.
  • with open으로도 가능하다. 당연히 option들도 유사하게 사용 가능하다.
import json

jsonl_data = []
with open("sample_file.jsonl", "r") as json_file:
    for line in json_file:
        jsonl_data.append(json.loads(line))

 

jsonl 파일 쓰기

import json

with open("sample_file.jsonl", "w", encoding="utf-8") as json_file:
	for data in json_data:
    	json_file.write(json.dumps(data, ensure_ascii=False))
        json_file.write("\n") # json을 여러 줄 쓰는 것이므로 줄바꿈을 넣어줘야 한다.