파일 읽기
발행: (2026년 2월 28일 오후 06:12 GMT+9)
1 분 소요
원문: Dev.to
Source: Dev.to
with 문과 함께 사용하기
with open("dream.txt", "r") as my_file:
contents = my_file.read()
print(type(contents), contents)
한 줄씩 읽어 리스트형으로 반환
with open("dream.txt", "r") as my_file:
content_list = my_file.readlines()
print(type(content_list))
print(content_list)
라인별 읽기 (while 루프)
with open("dream.txt", "r") as my_file:
i = 0
while True:
line = my_file.readline()
if not line:
break
print(f"{i} === {line.rstrip()}")
i += 1
인코딩 방식 지정
# 쓰기 모드 (utf-8 인코딩)
with open("count_log.txt", "w", encoding="utf8") as f:
for i in range(1, 11):
line = f"{i}번째 줄이다.\n"
f.write(line)
# 읽기 모드 (utf-8 인코딩)
with open("count_log.txt", "r", encoding="utf8") as f:
content = f.read()
print(content)
디렉토리 생성
import os
# 동일한 이름의 디렉토리가 없을 경우에만 생성
if not os.path.isdir("log"):
os.mkdir("log")