在 EOF 优雅退出

Exit gracefully at EOF

我正在尝试解析一个文件,其中始终存在一部分,而过去的部分是可选的。

for line in finp:
    # This part is always present
    for _ in range(int(ldata[2])):
        sdata = finp.readline()
        tdos.write(sdata)


    #This part may or may not be present
    for i in range(int(atoms)):
        next(finp)
        for j in range(int(ldata[2])):
            aatom[i][j] = [float(x) for x in
                           finp.readline().strip().split()]

问题是,如果可选部分不存在,next(finp) 给出错误:

    next(finp)
StopIteration

我试过:

for i in range(int(atoms)):
    if i is not None:
        next(finp)
        for j in range(int(ldata[2])):
            aatom[i][j] = [float(x) for x in
                           finp.readline().strip().split()]
    else:
        break

但这并不能解决问题。我发现许多以前的问题与 this 等问题相同,但无法解决此问题。

是否唯一的解决方法,如accepted ans中所述,是一次读取整个文件然后处理?

next() 默认设置为 return:

next(finp, None)

当给定第二个参数时,next() 捕获 一个 StopIteration 异常并 return 第二个参数。

另一种方法是自己抓 StopIteration;也许你想在那个时候跳出循环:

try:
    next(finp)
except StopIteration:
    break

请注意,您还混用了 file.readline()next(file)。由于 Python 2 中的实现细节,您将 运行 出现意外行为,因为这两种方法 共享它们的缓存。坚持在这里使用 next()(因为 for 循环也将 file 视为迭代器)。请参阅 File Objects 文档:

In order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right. However, using seek() to reposition the file to an absolute position will flush the read-ahead buffer.

如果您使用的是 Python 3,则可以忽略此警告,但最好还是坚持使用这两种方法中的一种。