文件读取
发布: (2026年2月28日 GMT+8 17:12)
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")