1. json 모듈: 파이썬 객체 ↔ JSON
import json
1-1. 파이썬 객체 → JSON 문자열
import json
data = {
"name": "Alice",
"age": 30,
"skills": ["python", "sql"],
"active": True,
}
s = json.dumps(data, ensure_ascii=False, indent=2)
print(s)
ensure_ascii=False : 한글 깨짐 방지
indent=2 : 보기 좋게 들여쓰기
1-2. JSON 문자열 → 파이썬 객체
import json
s = '{"name": "Alice", "age": 30, "skills": ["python", "sql"]}'
data = json.loads(s)
print(data["name"], data["skills"])
1-3. JSON 파일 저장/불러오기
import json
data = {"title": "테스트", "value": 123}
# 저장
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# 읽기
with open("data.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded)
- 설정 파일, 간단한 DB 대체, REST API 응답 저장 등에 자주 활용.
2. csv 모듈: 쉼표 구분 텍스트 처리
import csv
2-1. 기본 읽기: csv.reader
import csv
with open("data.csv", "r", encoding="utf-8", newline="") as f:
reader = csv.reader(f)
for row in reader:
print(row)
- 각
row는 list[str] 형태
- 헤더가 있을 경우 첫 줄을 따로 처리
with open("data.csv", "r", encoding="utf-8", newline="") as f:
reader = csv.reader(f)
header = next(reader) # 첫 줄
print("헤더:", header)
for row in reader:
print("데이터:", row)
2-2. DictReader: 헤더 기반 딕셔너리로 읽기
import csv
with open("data.csv", "r", encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["age"])
- 각 행이
dict로 들어와서 컬럼 이름으로 접근하기 쉽습니다.
2-3. csv.writer: 리스트 기반 쓰기
import csv
rows = [
["name", "age"],
["Alice", 30],
["Bob", 25],
]
with open("output.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)
writerow(row) : 한 행
writerows(list_of_rows) : 여러 행
2-4. DictWriter: 딕셔너리 기반 쓰기
import csv
fieldnames = ["name", "age"]
with open("output.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({"name": "Alice", "age": 30})
writer.writerow({"name": "Bob", "age": 25})
3. JSON ↔ CSV 변환 기본 패턴
3-1. JSON 리스트 → CSV
import json
import csv
json_data = "[\n {\"name\": \"Alice\", \"age\": 30},\n {\"name\": \"Bob\", \"age\": 25}\n]"
records = json.loads(json_data)
with open("people.csv", "w", encoding="utf-8", newline="") as f:
fieldnames = ["name", "age"]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(records)
3-2. CSV → JSON 리스트
import csv
import json
records = []
with open("people.csv", "r", encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
records.append(row)
with open("people.json", "w", encoding="utf-8") as f:
json.dump(records, f, ensure_ascii=False, indent=2)
4. 실무 예시
4-1. 설정 파일(config.json) 읽어서 경로/옵션 사용
import json
from pathlib import Path
config_path = Path("config.json")
config = json.loads(config_path.read_text(encoding="utf-8"))
data_dir = Path(config["data_dir"])
threshold = config.get("threshold", 0.5)
print("데이터 폴더:", data_dir)
print("임계값:", threshold)
4-2. 로그 CSV에서 특정 조건 필터링
import csv
with open("logs.csv", "r", encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
errors = [row for row in reader if row["level"] == "ERROR"]
print("에러 로그 개수:", len(errors))