티스토리 뷰
1. json 파일 읽고 쓰기
1) 읽기
대상 json
[
{"id": "this is id",
"category": "this is category",
"media_type": "this is media_type",
"media_sub_type": "this is media_sub_type",
"media_name": "this is media_name",
"size": "this is size",
"char_count": "this is char_count",
"publish_date": "this is publish_date",
"title": "this is title"}
]
읽기
import json
with open("target.json", "r", encoding="utf-8") as f:
taget_json = json.load(f)
print(len(target_json)) # list의 길이 1 출력
for i in range(len(target_json)):
print(target_json[i]["id"]) # "this is id" 출력
print(target_json[i]["title"]) # "this is title" 출력
2) 쓰기
import json
my_data = [{"id": "this is id", "title": "this is title"}]
with open("my_prac.json", "w", encoding="utf-8") as f: # 쓰기 모드(w)나 추가 모드(a)로 열기
json.dump(my_data, f) #json.dump를 이용하여 쓰기
쓰기 결과 json
[
{"id": "this is id",
"title": "this is title"}
]
2. jsonl (jsonlines) 파일 읽고 쓰기
1) 읽기
대상 jsonl => jsonl은 json이 여러 줄 있는 것
{"id": "this is id", publish_date": "this is publish_date", "title": "this is title"}
{"id": "this is id2", publish_date": "this is publish_date2", "title": "this is title2"}
{"id": "this is id3", publish_date": "this is publish_date3", "title": "this is title3"}
{"id": "this is id4", publish_date": "this is publish_date4", "title": "this is title4"}
읽기
import jsonlines
with jsonlines.open("target.jsonl") as f:
for line in f.iter():
print(line["id"]) # 각 json에 해당하는 "id" 출력
print(line["title"]) # 각 json에 해당하는 "title" 출력
2) 쓰기
import json
from collections import OrderedDict
my_data = OrderedDict()
my_data["id"] = "this is id"
my_data["title"] = "this is title"
with open("target_data.jsonl", "w", encoding="utf-8") as f:
json.dump(my_data, f, ensure_ascii=False) # ensure_ascii로 한글이 깨지지 않게 저장
f.write("\n") # json을 쓰는 것과 같지만, 여러 줄을 써주는 것이므로 "\n"을 붙여준다.
쓰기 결과 jsonl
{"id": "this is id", "title": "this is title"}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 베이즈정리
- #BOJ #유클리드호제법
- Rag
- LeetCode
- NAACL21
- DECI
- 베르누이분포
- #브루트포스
- 조건부확률
- CoT
- #information_retrieval
- two-pointers
- #BOJ #알고리즘 #1034번
- 확률과통계
- #BOJ #2467번 #투포인터알고리즘
- 이항분포
- iclr
- 인과관계추론
- Tensor
- KL_Divergence
- #BOJ #그리디알고리즘
- 이산확률분포
- PyTorch
- NumPy
- #BOJ
- 파이토치
- sliding window
- GCN
- emnlp2024
- #1405번
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함