파일 읽기

Published: (February 28, 2026 at 04:12 AM EST)
1 min read
Source: 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 views
Back to Blog

Related posts

Read more »

测试文章1DEV.to专属

!Cover image for 测试文章1DEV.to专属https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fexample.com%2Fimage1.jp...