You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对用open()打开的文件实现「un-readline()」回退读取功能?

实现文件读取的「un-readline()」功能

Python 标准库的文件对象本身没有内置的 unreadline() 方法,但可以通过以下两种方式实现类似需求:

方法一:利用文件指针定位(tell() + seek())

通过记录读取前的文件指针位置,在需要"回退"时将指针移回原位,就能让后续的 readline() 重新读取该行。

修改后的示例代码:

#!/bin/env python

fp = open("temp.txt", "r")

# 记录读取前的文件指针位置
pos = fp.tell()
# 读取一行
linein = fp.readline()
print(linein)

# 回退到之前记录的位置
fp.seek(pos)

# 再次读取同一行
linein = fp.readline()
print(linein)

方法二:封装自定义文件类,添加unreadline方法

如果希望更贴合你示例中的 unreadline() 调用方式,可以封装一个自定义类,通过缓存上一次读取的行来实现功能:

#!/bin/env python

class UnreadableFile:
    def __init__(self, file_obj):
        self.file = file_obj
        self._cached_line = None

    def readline(self):
        # 如果有缓存的行,优先返回缓存内容
        if self._cached_line is not None:
            line = self._cached_line
            self._cached_line = None
            return line
        # 没有缓存则读取文件,并缓存当前行
        line = self.file.readline()
        self._cached_line = line
        return line

    def unreadline(self):
        if self._cached_line is None:
            raise ValueError("没有可回退的行")
        # 无需额外操作,缓存的行会在下次readline时被优先返回
        pass

# 使用自定义类
fp = open("temp.txt", "r")
ufp = UnreadableFile(fp)

# 读取一行
linein = ufp.readline()
print(linein)

# 执行"un-readline"操作
ufp.unreadline()

# 再次读取同一行
linein = ufp.readline()
print(linein)

两种方法都能实现你的期望输出:

FIRST_LINE
FIRST_LINE

内容的提问来源于stack exchange,提问作者ysap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:13:32