# with 문으로 안전하게 파일 열기with open("data.txt", "r", encoding="utf-8") as f: content = f.read() # 전체 내용을 문자열로print(content)# 줄 단위 읽기with open("data.txt", "r", encoding="utf-8") as f: lines = f.readlines() # 줄 단위 리스트# 한 줄씩 순회 (메모리 효율적)with open("data.txt", "r", encoding="utf-8") as f: for line in f: print(line.strip()) # 줄바꿈 제거
2
파일 쓰기
Copy
# 새 파일 작성 (기존 내용 덮어쓰기)with open("output.txt", "w", encoding="utf-8") as f: f.write("첫째 줄\n") f.write("둘째 줄\n")# 여러 줄 한 번에 쓰기lines = ["라인 1\n", "라인 2\n", "라인 3\n"]with open("output.txt", "w", encoding="utf-8") as f: f.writelines(lines)# 추가 모드 (기존 내용 유지)with open("log.txt", "a", encoding="utf-8") as f: f.write("새로운 로그 항목\n")
import csv# 학습 로그 기록def log_training(filepath, epoch, train_loss, val_loss, accuracy): """학습 결과를 CSV로 기록합니다.""" file_exists = Path(filepath).exists() with open(filepath, "a", encoding="utf-8", newline="") as f: writer = csv.writer(f) if not file_exists: writer.writerow(["epoch", "train_loss", "val_loss", "accuracy"]) writer.writerow([epoch, f"{train_loss:.4f}", f"{val_loss:.4f}", f"{accuracy:.4f}"])# 학습 루프에서 사용for epoch in range(10): log_training("training_log.csv", epoch, 0.5/epoch, 0.6/epoch, 0.8+epoch*0.02)# 대용량 텍스트 파일 스트리밍 처리def process_large_file(filepath, batch_size=1000): """대용량 파일을 배치 단위로 처리합니다.""" batch = [] with open(filepath, "r", encoding="utf-8") as f: for line in f: batch.append(line.strip()) if len(batch) >= batch_size: yield batch batch = [] if batch: yield batch
with 문을 안 쓰면 어떻게 되나요?
파일을 수동으로 닫아야(f.close()) 합니다. 예외가 발생하면 닫히지 않아 데이터 손실이나 리소스 누수가 발생할 수 있습니다. 항상 with 문을 사용하세요.
CSV 대신 Pandas를 쓰면 안 되나요?
Pandas의 read_csv()가 더 편리하지만, 간단한 CSV 처리에는 표준 csv 모듈로 충분합니다. Pandas는 데이터 분석 탭에서 다룹니다.