Python - 7. 파일 입출력

2025. 1. 19. 19:11프로그래밍 언어/Python

Python에서는 파일 입출력을 통해 데이터를 저장하거나 읽어올 수 있습니다. 이 섹션에서는 텍스트 파일, CSV 파일, JSON 파일 처리 방법과 SQLite 데이터베이스 연동 방법을 다룹니다.


7.1 텍스트 파일 처리

텍스트 파일은 일반적인 문자열 데이터를 저장하거나 읽을 때 사용됩니다.

파일 열기 모드

  • r: 읽기 모드 (기본값)
  • w: 쓰기 모드 (파일이 없으면 생성, 기존 내용 삭제)
  • a: 추가 모드 (파일이 없으면 생성, 내용 뒤에 추가)
  • r+: 읽기 및 쓰기 모드
  • rb, wb: 바이너리 모드에서 읽기와 쓰기

파일 읽기

# 파일 읽기
try:
    with open("example.txt", "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("파일이 존재하지 않습니다.")
except IOError as e:
    print(f"파일 처리 중 오류 발생: {e}")

파일 쓰기

# 파일 쓰기
try:
    with open("example.txt", "w") as file:
        file.write("Hello, World!\nThis is a new line.")
except IOError as e:
    print(f"파일 쓰기 중 오류 발생: {e}")

바이너리 파일 처리

# 바이너리 파일 쓰기
with open("example.bin", "wb") as file:
    file.write(b"Binary data")

# 바이너리 파일 읽기
with open("example.bin", "rb") as file:
    data = file.read()
    print(data)  # b'Binary data'

파일에 줄 단위로 쓰기

# 줄 단위 쓰기
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example.txt", "w") as file:
    file.writelines(lines)

파일 줄 단위 읽기

# 줄 단위 읽기
with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())

7.2 CSV 파일 처리

CSV(Comma-Separated Values)는 데이터 저장 및 교환에 자주 사용됩니다. Python의 csv 모듈을 사용하여 처리할 수 있습니다.

CSV 파일 쓰기

import csv

# CSV 파일 쓰기
with open("data.csv", "w", newline="", encoding="utf-8") as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["Name", "Age", "City"])
    writer.writerow(["Alice", 30, "New York"])
    writer.writerow(["Bob", 25, "Los Angeles"])

CSV 파일 읽기

# CSV 파일 읽기
with open("data.csv", "r", encoding="utf-8") as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)

딕셔너리 형태로 CSV 처리

# 딕셔너리로 CSV 쓰기
with open("data.csv", "w", newline="", encoding="utf-8") as csvfile:
    fieldnames = ["Name", "Age", "City"]
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({"Name": "Alice", "Age": 30, "City": "New York"})
    writer.writerow({"Name": "Bob", "Age": 25, "City": "Los Angeles"})

# 딕셔너리로 CSV 읽기
with open("data.csv", "r", encoding="utf-8") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row)

CSV Dialect 옵션

csv 모듈은 다양한 파일 형식을 처리할 수 있도록 dialect 옵션을 제공합니다.

# Dialect 사용
with open("data.csv", "w", newline="", encoding="utf-8") as csvfile:
    writer = csv.writer(csvfile, delimiter=";", quotechar="'", quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["Name", "Age", "City"])
    writer.writerow(["Alice", 30, "New York"])

7.3 JSON 파일 처리

JSON(JavaScript Object Notation)은 데이터를 직렬화하고 교환하는 데 사용되는 경량 데이터 포맷입니다. Python의 json 모듈을 사용하여 JSON 데이터를 처리할 수 있습니다.

JSON 파일 쓰기

import json

# JSON 데이터 쓰기
data = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

with open("data.json", "w", encoding="utf-8") as jsonfile:
    json.dump(data, jsonfile, indent=4)

JSON 파일 읽기

# JSON 데이터 읽기
try:
    with open("data.json", "r", encoding="utf-8") as jsonfile:
        data = json.load(jsonfile)
        print(data)
except FileNotFoundError:
    print("JSON 파일이 존재하지 않습니다.")
except json.JSONDecodeError as e:
    print(f"JSON 디코딩 오류: {e}")

JSON 문자열 변환

# 파이썬 객체를 JSON 문자열로 변환
json_string = json.dumps(data, indent=4)
print(json_string)

# JSON 문자열을 파이썬 객체로 변환
parsed_data = json.loads(json_string)
print(parsed_data)

7.4 데이터베이스 연동 (SQLite)

SQLite는 가벼운 임베디드 데이터베이스입니다. Python의 sqlite3 모듈을 사용하여 처리할 수 있습니다.

데이터베이스 연결 및 테이블 생성

import sqlite3

# 데이터베이스 연결
conn = sqlite3.connect("example.db")

# 커서 객체 생성
cursor = conn.cursor()

# 테이블 생성
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    age INTEGER,
    city TEXT
)
""")

# 변경 사항 저장
conn.commit()

데이터 삽입

# 데이터 삽입
try:
    cursor.execute("INSERT INTO users (name, age, city) VALUES (?, ?, ?)",
                   ("Alice", 30, "New York"))
    conn.commit()
except sqlite3.Error as e:
    print(f"데이터 삽입 오류: {e}")

데이터 조회

# 데이터 조회
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
    print(row)

데이터 업데이트와 삭제

# 데이터 업데이트
cursor.execute("UPDATE users SET age = ? WHERE name = ?", (35, "Alice"))
conn.commit()

# 데이터 삭제
cursor.execute("DELETE FROM users WHERE name = ?", ("Alice",))
conn.commit()

트랜잭션 관리

SQLite는 기본적으로 자동 커밋 모드입니다. 트랜잭션을 명시적으로 관리하려면 다음을 사용할 수 있습니다:

try:
    conn.execute("BEGIN TRANSACTION")
    cursor.execute("INSERT INTO users (name, age, city) VALUES (?, ?, ?)",
                   ("Bob", 40, "Los Angeles"))
    conn.commit()
except sqlite3.Error as e:
    print(f"트랜잭션 오류: {e}")
    conn.rollback()

데이터베이스 연결 종료

# 연결 종료
conn.close()

파일 경로 보안

사용자 입력으로 파일 경로를 처리할 때는 os.path 모듈을 사용하여 보안을 강화합니다.

import os

filename = "../example.txt"  # 의도하지 않은 경로 접근 방지
secure_path = os.path.abspath(filename)
print(secure_path)

이번 섹션에서는 텍스트 파일, CSV 파일, JSON 파일, 그리고 SQLite 데이터베이스를 활용한 파일 입출력 방법을 다뤘습니다.

'프로그래밍 언어 > Python' 카테고리의 다른 글

Python - 9. 객체 지향 프로그래밍  (0) 2025.01.19
Python - 8. 예외 처리  (0) 2025.01.19
Python - 6. 딕셔너리와 튜플  (0) 2025.01.19
Python - 5. 함수  (0) 2025.01.19
Python - 4. 리스트와 문자열 심화  (0) 2025.01.19