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

自定义Python类EasyFile统计TXT文件行数时输出异常求助

问题分析

你的代码主要存在以下几个核心问题:

  1. readUntil方法的光标同步逻辑错误

    • 调用this.reader.read()会一次性读取光标后的全部内容,此时reader的内部指针会直接跳到文件末尾。后续调用this.moveCursor(this.cursor)试图同步光标,但reader指针已处于末尾,下次读取会直接得到空字符串,导致重复读取旧内容。
    • 处理完内容后,光标移动的计算逻辑有误,无法正确反映实际读取的字符数。
  2. moveCursorToLine的逻辑不符合预期

    • 该方法每次先将光标重置到文件开头,再循环lineNum次调用readUntil,实际行为是“读取前lineNum行”,而非“将光标移动到第lineNum行的起始位置”。这直接导致输出顺序错乱:lineCount=0时无输出,lineCount=1时才读取第一行。
  3. moveCursor的EOF判断存在漏洞

    • 当光标位置等于文件总长度时,temp.read(1)返回空,但检查charNum-1位置时会读取到文件最后一个字符,无法触发EOFError,导致循环无法终止,出现无限读取的情况。
修复后的代码
def main():
    file = EasyFile("numbers.txt")
    file.write("1, -2, 5, 0, 19, -7, end\n5, 5, -1, -10, 9, end")
    lineCount = 0
    while True:
        try:
            print(f"Line #{lineCount+1}")
            line_content = file.moveCursorToLine(lineCount)
            print(repr(line_content))
        except EOFError:
            break
        lineCount += 1
    print(f"The amount of lines are: {lineCount}")    

class EasyFile():
    def __init__(self, filename):
        self.filename = filename
        self.cursor = 0
        # 用w+模式打开单个文件对象,避免读写不同步问题
        self.file = open(filename, "w+")
        self.file.seek(self.cursor)

    def moveCursor(self, charNum):
        file_size = self._get_file_size()
        if charNum > file_size:
            raise EOFError
        self.cursor = charNum
        self.file.seek(charNum)

    def _get_file_size(self):
        # 获取文件总长度,不影响当前光标位置
        current_pos = self.file.tell()
        self.file.seek(0, 2)
        size = self.file.tell()
        self.file.seek(current_pos)
        return size

    def moveCursorToLine(self, lineNum):
        # 移动光标到指定行起始位置,并返回该行内容
        self.moveCursor(0)
        current_line = 0
        line_content = ""
        while current_line <= lineNum:
            char = self.file.read(1)
            if not char:
                # 到达文件末尾
                if current_line == lineNum:
                    self.cursor = self.file.tell()
                    return line_content
                raise EOFError
            if char == "\n":
                if current_line == lineNum:
                    self.cursor = self.file.tell()
                    return line_content
                line_content = ""
                current_line += 1
            else:
                line_content += char
        # 处理最后一行无换行符的情况
        self.cursor = self.file.tell()
        return line_content

    def write(self, string):
        self.file.seek(self.cursor)
        self.file.write(string)
        self.file.flush()
        self.cursor += len(string)

main()
修复说明
  1. 合并读写文件对象

    • 改用w+模式打开单个文件对象,避免同时打开读写两个对象导致的内容不同步问题,简化光标同步逻辑。
  2. 重写moveCursorToLine方法

    • 从文件开头逐字符读取,精准定位到目标行的起始位置,同时返回该行内容,完全符合“移动光标到指定行”的预期行为,还处理了最后一行无换行符的边界情况。
  3. 优化光标与EOF判断

    • 新增_get_file_size方法获取文件总长度,当要移动的光标位置超过文件大小时直接触发EOFError,逻辑更清晰可靠。
  4. 移除冗余方法

    • 原readUntil的功能已整合到行定位逻辑中,避免了原方法的光标同步问题,简化了代码结构。

运行修复后的代码,会得到你期望的输出:

Line #1
'1, -2, 5, 0, 19, -7, end'
Line #2
'5, 5, -1, -10, 9, end'
The amount of lines are: 2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 20:35:58