2015-11-27 25 views
2

我在Windows 7 64字節中使用Spyder 2.3.7和Python 2.7.10。Python file.tell()給出錯誤的值

我想讀取文本文件,並且想要在讀取一行後讀取文件中的位置;主要原因是稍後可以在完成一些搜索後返回到文件中。 不管,當我使用下面的代碼:

FileOrig = "testtext{Number}"; 
for index_file in range(1, 2): 
    fileName = FileOrig.format(Number = str(index_file)) 

    ff = open(fileName, "rb") 
    numline = 1; 
    for line in ff: 
     numline = numline + 1; 
     position = ff.tell(); 
     print(position); 

    ff.close() 

凡文件testtext1的內容(這僅僅是一個例子):

Overall accuracy 
Overall accuracy 
2.2603e+03 
2.3179e+03 
2.5265e+03 
4.8463e+03 
1.7547e+03 
3.0143e+03 
3.1387e+03 


Overall accuracy 
Overall accuracy 
2.2414e+03 
3.9409e+03 
1.8902e+03 
4.1157e+03 


Overall accuracy 
Overall accuracy 
2.2275e+03 
1.3579e+03 
2.3712e+03 
6.4970e+03 
5.8891e+03 



    SPLITBIB.STY  -- N. MARKEY <[email protected]> 
        v1.17 -- 2005/12/22 

This package allows you to split a bibliography into several categories 
and subcategories. It does not depend on BibTeX, and any bibliography 
may be split and reordered. 

split­bib – Split and re­order your bib­li­og­ra­phy 

This pack­age en­ables you to split a bib­li­og­ra­phy into sev­eral cat­e­gories and sub­cat­e­gories. It does not de­pend on BibTeX: any bib­li­og­ra­phy may be split and re­ordered. 

這就產生了我很奇怪的輸出:

916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 
916 

上面的代碼有什麼問題,如果我使用二進制讀取或沒有不同,沒什麼不同。

回答

1

因爲迭代涉及使用預讀緩衝區,所以混合迭代文件和使用文件方法將不起作用。使用file.readline而是使用file.tell

... 
while True: 
    line = ff.readline() 
    if not line: 
     break 
    numline = numline + 1 
    position = ff.tell() 
    print(position) 
... 

根據file.next documentation

一個文件對象是自己的迭代器,例如iter(f)回報f (除非f關閉)。當文件用作迭代器時,通常在for循環中(例如,for line in f: print line.strip()), next()方法被重複調用。此方法返回下一個輸入 行,或者在打開文件時觸發EOF時提取StopIteration 進行讀取(當文件打開進行寫入時行爲未定義)。 爲了使for循環成爲循環遍歷文件的 行(非常常見的操作)的最有效方式,next()方法使用隱藏的預讀緩衝區。由於使用預讀 緩衝區,將next()與其他文件方法(如readline()) 組合不起作用。但是,使用seek()將文件重新定位到 絕對位置將刷新預讀緩衝區。

+0

作品完美,感謝您的信息,抱歉,沒有足夠的代表來投票回答。 – RobertoST