Python 파일 처리 | 읽기, 쓰기, CSV, JSON 완벽 정리
이 글의 핵심
Python 파일 처리에 대한 실전 가이드입니다. 읽기, 쓰기, CSV, JSON 완벽 정리 등을 예제와 함께 상세히 설명합니다.
들어가며
”파일 처리는 실무의 기본”
파일 읽기/쓰기는 데이터 저장, 로그 기록, 설정 관리 등 실무에서 필수입니다.
1. 텍스트 파일
파일 읽기
디스크에 있는 텍스트 파일은 책장에 꽂힌 공책과 비슷합니다. open으로 한 번 펼치면 줄 단위로 읽거나 한꺼번에 읽을 수 있고, encoding='utf-8'을 빼먹으면 한글이 깨질 수 있으므로 습관처럼 적어 두는 것이 좋습니다.
# 방법 1: 전체 읽기
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
# 방법 2: 줄 단위 읽기
with open('data.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
print(line.strip())
# 방법 3: 반복문 (메모리 효율적)
with open('data.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip())
파일 쓰기
# 덮어쓰기 (w)
with open('output.txt', 'w', encoding='utf-8') as f:
f.write("첫 번째 줄\n")
f.write("두 번째 줄\n")
# 추가 (a)
with open('output.txt', 'a', encoding='utf-8') as f:
f.write("세 번째 줄\n")
# 여러 줄 쓰기
lines = ["라인 1\n", "라인 2\n", "라인 3\n"]
with open('output.txt', 'w', encoding='utf-8') as f:
f.writelines(lines)
2. CSV 파일
CSV 읽기
import csv
# 방법 1: 리스트로 읽기
with open('data.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
header = next(reader) # 첫 줄 (헤더)
for row in reader:
print(row)
# 방법 2: 딕셔너리로 읽기 (권장)
with open('data.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
print(row['name'], row['age'])
CSV 쓰기
import csv
# 방법 1: 리스트로 쓰기
data = [
['이름', '나이', '도시'],
['철수', 25, '서울'],
['영희', 30, '부산']
]
with open('output.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(data)
# 방법 2: 딕셔너리로 쓰기
data = [
{'name': '철수', 'age': 25, 'city': '서울'},
{'name': '영희', 'age': 30, 'city': '부산'}
]
with open('output.csv', 'w', newline='', encoding='utf-8') as f:
fieldnames = ['name', 'age', 'city']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
3. JSON 파일
JSON 읽기
import json
# 파일에서 읽기
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
print(data)
# 문자열에서 읽기
json_str = '{"name": "철수", "age": 25}'
data = json.loads(json_str)
print(data['name']) # 철수
JSON 쓰기
import json
data = {
"name": "철수",
"age": 25,
"hobbies": ["독서", "영화", "운동"],
"address": {
"city": "서울",
"district": "강남구"
}
}
# 파일로 쓰기
with open('output.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# 문자열로 변환
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
4. 경로 처리 (pathlib)
pathlib 사용
from pathlib import Path
# 현재 디렉토리
current = Path.cwd()
print(current)
# 경로 결합
data_dir = Path('data')
file_path = data_dir / 'users.json'
print(file_path) # data/users.json
# 파일 존재 확인
if file_path.exists():
print("파일 있음")
# 디렉토리 생성
data_dir.mkdir(exist_ok=True)
# 파일 읽기/쓰기
file_path.write_text("Hello, World!", encoding='utf-8')
content = file_path.read_text(encoding='utf-8')
print(content)
# 파일 정보
print(file_path.name) # users.json
print(file_path.stem) # users
print(file_path.suffix) # .json
print(file_path.parent) # data
5. 실전 예제
로그 파일 분석
from collections import Counter
from pathlib import Path
def analyze_log(log_file):
"""로그 파일에서 에러 통계"""
error_counts = Counter()
with open(log_file, 'r', encoding='utf-8') as f:
for line in f:
if 'ERROR' in line:
error_type = line.split(':')[1].strip()
error_counts[error_type] += 1
return error_counts
# 사용
errors = analyze_log('app.log')
for error, count in errors.most_common(5):
print(f"{error}: {count}회")
설정 파일 관리
import json
from pathlib import Path
class Config:
def __init__(self, config_file='config.json'):
self.config_file = Path(config_file)
self.data = self.load()
def load(self):
if self.config_file.exists():
with open(self.config_file, 'r', encoding='utf-8') as f:
return json.load(f)
return {}
def save(self):
with open(self.config_file, 'w', encoding='utf-8') as f:
json.dump(self.data, f, ensure_ascii=False, indent=2)
def get(self, key, default=None):
return self.data.get(key, default)
def set(self, key, value):
self.data[key] = value
self.save()
# 사용
config = Config()
config.set('database_url', 'localhost:5432')
print(config.get('database_url'))
with 문·인코딩·경로 확인 (한눈에 보는 패턴)
파일은 열었다가 닫지 않으면 자원이 새는 창문과 같아서, with로 열면 블록을 빠져나올 때 자동으로 닫힙니다. Windows·Mac 혼용 환경에서는 encoding='utf-8'을 명시하는 것이 깨짐을 막는 데 도움이 됩니다.
# ✅ with 문 사용 (자동으로 파일 닫힘)
with open('file.txt', 'r') as f:
content = f.read()
# ❌ 수동으로 닫기 (예외 발생 시 문제)
f = open('file.txt', 'r')
content = f.read()
f.close()
# ✅ encoding 명시
with open('file.txt', 'r', encoding='utf-8') as f:
pass
# ✅ 파일 존재 확인
from pathlib import Path
if Path('file.txt').exists():
# 파일 처리
pass
정리
핵심 요약
- 텍스트 파일:
with open(..., encoding='utf-8')로 읽고 쓰기 - CSV:
csv모듈의DictReader/DictWriter로 표 형태 처리 - JSON:
json.load/json.dump로 설정·API 응답 저장 - 경로:
pathlib.Path로 OS 차이를 줄이고 가독성 확보 - 로그·대용량: 줄 단위 순회로 메모리 부담 줄이기
이어서 읽기
- 예외 처리에서 파일 입출력 중 난 오류를 다루는 방법
- 파일 자동화에서 반복 작업 스크립트 예시
관련 글
- Python 시리즈 전체 보기
- Python 환경 설정 | Windows/Mac에서 Python 설치하고 시작하기
- Python 기본 문법 | 변수, 연산자, 조건문, 반복문 완벽 가이드
- Python 자료형 | 리스트, 딕셔너리, 튜플, 세트 완벽 가이드