728x90
이 글에서 다루는 개념
Python에서는 다양한 형식의 파일을 읽고 쓰는 기능을 제공합니다.
이번 글에서는 다음 내용을 학습합니다.
- 파일 입출력(File I/O) 기초
- 텍스트 파일 읽기/쓰기 (.txt)
- CSV 파일 다루기 (.csv)
- JSON 파일 다루기 (.json)
- YAML 파일 다루기 (.yaml)
1️⃣ 텍스트 파일 입출력 (.txt)
🔹 파일 쓰기 (write)
open() 함수를 사용하여 파일을 생성하고 데이터를 저장할 수 있습니다.
# 파일 쓰기 (w: 덮어쓰기 모드)
with open("example.txt", "w") as f:
f.write("Hello, Python!\n")
f.write("파일 입출력을 배워봅시다.")
print("파일이 성공적으로 저장되었습니다.")
📌 파일 모드 종류
- "w" → 쓰기 모드 (파일이 존재하면 덮어씀)
- "a" → 추가 모드 (기존 파일에 데이터 추가)
- "r" → 읽기 모드 (기본값)
🔹 파일 읽기 (read)
파일을 읽을 때 read(), readline(), readlines()를 사용할 수 있습니다.
# 파일 읽기
with open("example.txt", "r") as f:
content = f.read()
print(content)
📌 파일 읽기 함수 비교
함수 | 설명 |
read() | 전체 파일을 문자열로 읽음 |
readline() | 한 줄씩 읽음 |
readlines() | 모든 줄을 리스트로 반환 |
# 여러 줄을 리스트로 읽기
with open("example.txt", "r") as f:
lines = f.readlines()
print(lines)
2️⃣ CSV 파일 다루기 (.csv)
🔹 CSV 파일 쓰기
Python의 csv 모듈을 사용하면 CSV 파일을 쉽게 다룰 수 있습니다.
import csv
# CSV 파일 쓰기
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age", "City"]) # 헤더
writer.writerow(["Alice", 25, "Seoul"])
writer.writerow(["Bob", 30, "Busan"])
print("CSV 파일이 생성되었습니다.")
🔹 CSV 파일 읽기
csv.reader()를 사용하여 CSV 데이터를 읽을 수 있습니다.
# CSV 파일 읽기
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
📌 CSV 다루기 꿀팁
- csv.DictWriter() → 딕셔너리 형식으로 CSV 저장
- csv.DictReader() → 딕셔너리 형태로 CSV 읽기
with open("data.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["Name"], row["Age"])
3️⃣ JSON 파일 다루기 (.json)
JSON은 키-값 형태의 데이터 저장 형식으로, API 통신에서 자주 사용됩니다.
🔹 JSON 파일 쓰기 (dump)
import json
data = {
"name": "Alice",
"age": 25,
"city": "Seoul"
}
# JSON 파일 저장
with open("data.json", "w") as f:
json.dump(data, f, indent=4)
print("JSON 파일이 생성되었습니다.")
📌 json.dump() vs json.dumps() 차이
- json.dump(data, file) → 파일로 저장
- json.dumps(data) → 문자열(JSON 포맷)로 변환
🔹 JSON 파일 읽기 (load)
# JSON 파일 읽기
with open("data.json", "r") as f:
data = json.load(f)
print(data) # {'name': 'Alice', 'age': 25, 'city': 'Seoul'}
4️⃣ YAML 파일 다루기 (.yaml)
YAML은 가독성이 높은 데이터 포맷으로, 설정 파일에서 자주 사용됩니다.
Python에서는 PyYAML 패키지를 사용하여 YAML 파일을 다룰 수 있습니다.
📌 PyYAML 설치 (필요 시)
pip install pyyaml
🔹 YAML 파일 쓰기 (dump)
import yaml
data = {
"name": "Alice",
"age": 25,
"city": "Seoul"
}
# YAML 파일 저장
with open("data.yaml", "w") as f:
yaml.dump(data, f)
print("YAML 파일이 생성되었습니다.")
🔹 YAML 파일 읽기 (load)
# YAML 파일 읽기
with open("data.yaml", "r") as f:
data = yaml.safe_load(f)
print(data) # {'name': 'Alice', 'age': 25, 'city': 'Seoul'}
📌 YAML과 JSON 비교
- JSON → { "name": "Alice", "age": 25 }
- YAML →
name: Alice age: 25
📌 실전 문제: 파일 입출력 연습하기
✅ 문제 1: 텍스트 파일에 문자열 저장 후 읽기
📌 "hello.txt" 파일을 생성하고 "Hello, Python!"을 저장한 뒤 다시 읽어 출력하세요.
# 🔽 여기에 코드 작성
with open("hello.txt", "w") as f:
f.write("Hello, Python!")
with open("hello.txt", "r") as f:
content = f.read()
print(content) # Hello, Python!
✅ 문제 2: CSV 파일을 생성하고 데이터 저장 후 읽기
📌 이름, 나이, 도시 정보를 포함하는 CSV 파일을 생성하고 저장한 후 출력하세요.
import csv
# 🔽 여기에 코드 작성
import csv
# CSV 파일 쓰기
with open("people.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Alice", 25, "Seoul"])
writer.writerow(["Bob", 30, "Busan"])
# CSV 파일 읽기
with open("people.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
✅ 문제 3: JSON 파일 저장 및 로드
📌 딕셔너리 데이터를 JSON 파일로 저장한 후 다시 읽어 출력하세요.
import json
# 🔽 여기에 코드 작성
import json
data = {"name": "Alice", "age": 25}
# JSON 파일 저장
with open("data.json", "w") as f:
json.dump(data, f)
# JSON 파일 읽기
with open("data.json", "r") as f:
data = json.load(f)
print(data) # {'name': 'Alice', 'age': 25}
728x90
'Data Engineering > python' 카테고리의 다른 글
EP10 | Python 심화 개념 #4 | 예외 처리와 로깅 (Logging & Exception Handling) (0) | 2025.03.19 |
---|---|
EP09 | Python 심화 개념 #3 | 정규표현식(Regex)과 문자열 처리 (0) | 2025.03.19 |
EP07 | Python 심화 개념 #1 | 이터레이터와 제너레이터 (0) | 2025.03.19 |
EP06 | Python 클래스와 객체지향 프로그래밍 (OOP) (0) | 2025.03.19 |
EP05 | Python 함수와 스코프 (Global, Local, Lambda 함수) (0) | 2025.03.19 |