파일 읽기

발행: (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")
0 조회
Back to Blog

관련 글

더 보기 »

구리지 않은 시맨틱 무효화

캐싱 문제 웹 애플리케이션을 어느 정도 기간 동안 작업해 본 사람이라면 캐싱에 대한 상황을 잘 알 것입니다. 캐시를 추가하면 모든 것이 빨라지고, 그 다음에 누군가…

그룹별 배열 뒤집기

문제 설명: 주어진 크기 k의 그룹으로 배열을 뒤집는다. 배열은 길이 k인 연속적인 청크(윈도우)로 나뉘며, 각 청크는 뒤집힌다.