2017-10-18 68 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