Reputation: 5347
I have a series of textfiles.
They all end with a float, without a preceding whitespace
...foo123.456
. The float has an unbounded number of digits.
the files are large so I would like to avoid reading them completely in memory. They have also different sizes.
How to avoid readgin the entire file?
Upvotes: 0
Views: 56
Reputation: 77349
Just read the last few bytes and use a regular expression in order to extract the float number.
Untested:
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')
Upvotes: 2