文件读取

发布: (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")
0 浏览
Back to Blog

相关文章

阅读更多 »

不糟糕的语义失效

缓存问题 如果你在 Web 应用上工作了一段时间,你就会了解缓存的情况。你加入缓存,一切都变快了,然后有人……

按组反转数组

问题描述:将数组按给定大小 k 分组后逆序。数组被划分为长度为 k 的连续块(窗口),每个块都被逆序。