03_파이썬(Python)

파이썬(Python) 기본 문법: 파일 입출력 (File I/O)

tothebest 2025. 8. 23. 16:00
728x90

안녕하세요

프로그램은 종종 파일에서 데이터를 읽거나, 새로운 파일을 생성해 결과를 저장해야 합니다.
파이썬은 간단한 문법으로 텍스트 파일을 읽고 쓸 수 있도록 지원합니다.

1. 파일 열기와 닫기

파이썬에서는 open() 함수를 사용하여 파일을 열고,
작업이 끝난 후 close()로 닫습니다.

f = open("example.txt", "w")  # 쓰기 모드로 열기
f.write("Hello, Python!\n")
f.close()

example.txt 파일이 생성되고, 안에 "Hello, Python!"이 기록됩니다.

 

2. 파일 열기 모드

  • "r" : 읽기 모드 (기본값, 파일이 없으면 오류 발생)
  • "w" : 쓰기 모드 (기존 내용 삭제 후 새로 작성)
  • "a" : 추가 모드 (기존 내용 뒤에 이어쓰기)
  • "rb", "wb" : 바이너리 모드 (이미지, 동영상 파일 등)

3. 파일 읽기

예시: sample.txt 파일 내용

Python
Java
C++

 

f = open("sample.txt", "r")
content = f.read()
print(content)
f.close()

 

실행 결과

Python
Java
C++

 

줄 단위로 읽기

f = open("sample.txt", "r")
for line in f:
    print(line.strip())
f.close()

 

4. with 구문 (권장 방법)

with 구문을 쓰면 자동으로 파일이 닫히므로 편리합니다.

with open("example.txt", "w") as f:
    f.write("This is safer!\n")

with open("example.txt", "r") as f:
    print(f.read())

 

 

5. 파일 다루기 확장 (JSON / CSV)

(1) JSON 파일

import json

data = {"name": "Alice", "age": 25}

# 저장
with open("data.json", "w") as f:
    json.dump(data, f)

# 불러오기
with open("data.json", "r") as f:
    loaded = json.load(f)

print(loaded)  # {'name': 'Alice', 'age': 25}

 

(2) CSV 파일

import csv

# 쓰기
with open("score.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Score"])
    writer.writerow(["Tom", 90])
    writer.writerow(["Jane", 85])

# 읽기
with open("score.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

 

실행 결과

['Name', 'Score']
['Tom', '90']
['Jane', '85']

 

 

▣ 정리

  • open("파일명", "모드")로 파일 열기
  • "r", "w", "a" 모드를 자주 사용
  • with 구문을 사용하면 안전하게 파일을 다룰 수 있음
  • JSON, CSV 파일도 쉽게 읽고 쓸 수 있음

다음 글에서는 예외 처리 (try-except)를 배워보겠습니다.

 

 

감사합니다.

728x90