2016-07-08 143 views
1

我想解析一個文件,其中有一部分總是存在,而過去的部分是可選的。在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一樣的問題,但無法解決這個問題。

解決問題的唯一方法就是接受的答案是一次讀取整個文件然後處理?

回答

4

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,你可以忽略此警告,但你仍然是最好堅持使用這兩種方法之一。