Python 3 遍历文件直到 EOF。文件不仅仅是一组需要处理的相似行

Python 3 going through a file until EOF. File is not just a set of similar lines needing processing

"How do I do "while not eof(file)"

类型问题的答案

没有完全涵盖我的问题

我有一个格式类似于

的文件

header块

数据

另一个header块

更多数据(每个数据块中有任意数量的数据行)

...

不知道有多少header-data套

我已成功读取第一个块,然后使用循环查找数据块末尾的空白行来读取一组数据。

我不能只使用 "for each line in openfile" 类型的方法,因为我需要一次读取一个 header-data 块然后处理它们。

如何检测最后一个 header-data 块。

我目前的做法是使用try except构造,等待异常。不是很优雅。

没有看到您的任何代码就很难回答...

但我猜你正在用 fp.read():

读取文件
fp = open("a.txt")
while True:
    data = fp.read()

改为:

  1. 尝试始终传递您期望的数据长度
  2. 检查读取的chunck是否为空串,不是None

例如:

fp = open("a.txt")
while True:
    header = fp.read(headerSize)
    if header is '':
        # End of file
        break
    read_dataSize_from_header
    data = fp.read(dataSize)
    if data is '':
        # Error reading file
        raise FileError('Error reading file')
    process_your_data(data)

这是一段时间后的事,但我 post 这是为其他进行此搜索的人准备的。 适当调整后的以下脚本将读取文件并传送行,直到 EOF。

"""

Script to read a file until the EOF

"""
def get_all_lines(the_file):
    for line in the_file:
        if line.endswith('\n'):
            line = line[:-1]
        yield line


line_counter = 1
data_in = open('OAall.txt')
for line in get_all_lines(data_in):
    print(line)
    print(line_counter)
    line_counter += 1

data_in.close()