在EOF处优雅地退出

在EOF处优雅地退出

问题描述:

我想解析一个文件,其中有一部分总是存在,而过去的部分是可选的。在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一样的问题,但无法解决这个问题。

解决问题的唯一方法就是接受的答案是一次读取整个文件然后处理?

next()默认返回:

next(finp, None) 

当有第二个参数,next()一个StopIteration异常并返回第二个参数来代替。

另一种方法是自己抓住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,你可以忽略此警告,但你仍然是最好坚持使用这两种方法之一。