본문으로 건너뛰기 Python 파일 처리 | 읽기, 쓰기, CSV, JSON 완벽 정리

Python 파일 처리 | 읽기, 쓰기, CSV, JSON 완벽 정리

Python 파일 처리 | 읽기, 쓰기, CSV, JSON 완벽 정리

이 글의 핵심

Python 파일 처리: 읽기, 쓰기, CSV, JSON 텍스트 파일·CSV 파일.

들어가며

”파일 처리는 실무의 기본”

파일 읽기/쓰기는 데이터 저장, 로그 기록, 설정 관리 등 실무에서 필수입니다.

실무 활용 사례: 데이터 분석, 웹 개발, 자동화 프로젝트에서 실제로 사용한 패턴과 코드를 바탕으로 정리했습니다. 초보자가 흔히 겪는 오류와 해결법을 포함합니다.

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

정리

핵심 요약

  1. 텍스트 파일: with open(..., encoding='utf-8')로 읽고 쓰기
  2. CSV: csv 모듈의 DictReader / DictWriter로 표 형태 처리
  3. JSON: json.load / json.dump로 설정·API 응답 저장
  4. 경로: pathlib.Path로 OS 차이를 줄이고 가독성 확보
  5. 로그·대용량: 줄 단위 순회로 메모리 부담 줄이기

이어서 읽기


관련 글


자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. Python 파일 처리: 읽기, 쓰기, CSV, JSON 완벽 정리. 텍스트 파일·CSV 파일로 흐름을 잡고 원리·코드·실무 적용을 한글로 정리합니다. Python·파일처리·file 중심으로 설명합니다. Start … 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. Python 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

Python, 파일처리, file, CSV, JSON, pathlib, with 등으로 검색하시면 이 글이 도움이 됩니다.