open() 함수, 파일 모드(r, w, a), read, readline, readlines, with문, CSV 파일 처리.open(파일명, 모드)로 연다.r : 읽기 (read)w : 쓰기 (write, 기존 내용 삭제됨)a : 추가 (append, 기존 내용 뒤에 이어쓰기)f = open("a.txt", "w") # 쓰기 모드로 파일 생성
f.write("Hello World")
f.close()
파일객체.write(내용)으로 텍스트 기록f = open("test.txt", "w")
f.write("첫 번째 줄\n")
f.write("두 번째 줄\n")
f.close()
f = open("test.txt", "r", encoding="utf-8")
data = f.read()
print(data)
f.close()
\n 포함됨f = open("test.txt", "r", encoding="utf-8")
line = f.readline()
print(line.strip()) # strip()으로 개행 제거
f.close()
f = open("test.txt", "r", encoding="utf-8")
lines = f.readlines()
for l in lines:
print(l.strip())
f.close()
f = open("test.txt", "a")
f.write("추가된 줄\n")
f.close()
기존 내용 뒤에 이어서 기록
with문 사용 시 파일을 자동으로 close() 처리with open("test.txt", "r", encoding="utf-8") as f:
data = f.read()
print(data)
, 로 구분된 텍스트 형식import csv
with open("data.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["이름", "나이", "국가"])
writer.writerow(["철수", 25, "한국"])
writer.writerow(["John", 30, "USA"])
Ctrl + F8)F10)open, with, read, write의 차이와, CSV 파일의 구조를 배움