2017-10-18 70 views
0

我有一系列文本文件。 它們都以浮點形式結束,沒有前面的空格 ...foo123.456。浮點數有無限數量。在文件末尾讀取一個數字

文件很大,所以我想避免在內存中完全讀取它們。 他們也有不同的大小。

如何避免readgin整個文件?

+1

你可以用'file.seek',提示可以在這裏找到:https://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using -python – Blorgbeard

+0

雖然 – ErroriSalvo

+1

浮點數可以有任意長度@Liborio任意長度不應該只要你知道*最大長度。只需在文件末尾讀取一堆字符,然後向後搜索數字開頭的位置。 –

回答

2

只讀最後幾個字節並使用正則表達式來提取浮點數。

未經測試:

import re 

with open('/path/to/file.txt') as input_file: 
    input_file.seek(-100, 2) 
    last_100_bytes = input_file.read() 
    match = re.search(r'\D(\d+\.\d+)$', last_100_bytes) 
    if match: 
     print('The float is {}'.format(match.group(0))) 
    else: 
     print('no float found at the end of the file') 
+0

我認爲這畢竟是答案......閱讀100字節的結束時間不像@Paulo Scardine所暗示的那樣微不足道 – ErroriSalvo