본문 바로가기
개발&프로그래밍

[python] 파일 입출력 기초 가이드

by 재아군 2024. 11. 20.

[Python] 파일 입출력 기초 가이드

 

파일 입출력은 프로그래밍의 기본이자 필수 요소다.

Python에서 파일을 다루는 방법부터 실전에서 자주 사용하는 패턴까지 알아보자.

 

텍스트 파일 읽기/쓰기

기본적인 파일 읽기

# 전체 파일 읽기
with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

# 한 줄씩 읽기
with open('example.txt', 'r', encoding='utf-8') as file:
    for line in file:
        print(line.strip())  # strip()으로 줄바꿈 제거

# 모든 줄을 리스트로 읽기
with open('example.txt', 'r', encoding='utf-8') as file:
    lines = file.readlines()

 

파일 쓰기

# 새로운 파일 생성하고 쓰기
with open('output.txt', 'w', encoding='utf-8') as file:
    file.write('Hello, World!\n')
    file.write('This is a new line.')

# 기존 파일에 추가하기
with open('output.txt', 'a', encoding='utf-8') as file:
    file.write('\nAppending a new line.')

# 여러 줄 한번에 쓰기
lines = ['Line 1', 'Line 2', 'Line 3']
with open('output.txt', 'w', encoding='utf-8') as file:
    file.writelines(f'{line}\n' for line in lines)

 

CSV 파일 다루기

CSV 읽기

import csv

# CSV 파일 읽기
with open('data.csv', 'r', encoding='utf-8') as file:
    csv_reader = csv.reader(file)
    header = next(csv_reader)  # 헤더 row 읽기
    for row in csv_reader:
        print(row)

# Dictionary 형태로 읽기
with open('data.csv', 'r', encoding='utf-8') as file:
    csv_reader = csv.DictReader(file)
    for row in csv_reader:
        print(row)  # 헤더를 key로 사용

CSV 쓰기

# 기본 CSV 쓰기
data = [
    ['Name', 'Age', 'City'],
    ['John', '30', 'New York'],
    ['Jane', '25', 'Boston']
]

with open('output.csv', 'w', newline='', encoding='utf-8') as file:
    csv_writer = csv.writer(file)
    csv_writer.writerows(data)

# Dictionary 데이터 쓰기
dict_data = [
    {'Name': 'John', 'Age': '30', 'City': 'New York'},
    {'Name': 'Jane', 'Age': '25', 'City': 'Boston'}
]

with open('output.csv', 'w', newline='', encoding='utf-8') as file:
    fieldnames = ['Name', 'Age', 'City']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()  # 헤더 쓰기
    writer.writerows(dict_data)

 

with 문 활용

with 문의 장점

# 잘못된 방법 (파일이 닫히지 않을 수 있음)
file = open('example.txt', 'r', encoding='utf-8')
content = file.read()
file.close()

# 올바른 방법 (자동으로 파일이 닫힘)
with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()

# 여러 파일 동시에 다루기
with open('input.txt', 'r', encoding='utf-8') as in_file, \
     open('output.txt', 'w', encoding='utf-8') as out_file:
    content = in_file.read()
    out_file.write(content.upper())

 

경로 처리

pathlib 활용

from pathlib import Path

# 현재 작업 디렉토리
current_path = Path.cwd()
print(current_path)

# 경로 생성
data_path = Path('data')
file_path = data_path / 'example.txt'

# 경로 확인
print(file_path.exists())
print(file_path.is_file())
print(file_path.is_dir())

# 디렉토리 생성
new_dir = Path('new_directory')
new_dir.mkdir(exist_ok=True)

# 파일 목록 가져오기
for file in Path('data').glob('*.txt'):
    print(file)

 

os.path 활용

import os

# 경로 결합
path = os.path.join('folder', 'subfolder', 'file.txt')

# 절대 경로 얻기
abs_path = os.path.abspath('file.txt')

# 경로 분리
directory = os.path.dirname(path)
filename = os.path.basename(path)

# 확장자 분리
name, ext = os.path.splitext('file.txt')

 

실전 활용 예제

로그 파일 분석

def analyze_log(log_path):
    error_count = 0
    with open(log_path, 'r', encoding='utf-8') as file:
        for line in file:
            if 'ERROR' in line:
                error_count += 1
                print(f"Error found: {line.strip()}")
    return error_count

# 사용 예
errors = analyze_log('app.log')
print(f"Total errors found: {errors}")

 

파일 백업

from datetime import datetime
import shutil

def backup_file(file_path):
    # 백업 파일 이름 생성
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    backup_path = f"{file_path}.{timestamp}.backup"

    # 파일 복사
    shutil.copy2(file_path, backup_path)
    print(f"Backup created: {backup_path}")

# 사용 예
backup_file('important_data.txt')

 

댓글