Let exception fire or return None
Cecil Westerhof
Cecil at decebal.nl
Thu Apr 30 08:22:08 EDT 2015
Op Thursday 30 Apr 2015 13:26 CEST schreef Cecil Westerhof:
>> try:
>> [line] = itertools.islice(f, index, index+1)
>> except ValueError:
>> raise IndexError
>> return line.rstrip()
>
> In my case it is not important. (The biggest file I use has between
> 100 and 200 lines), but I publish it, so I should do my best to make
> it so lean as possible.
Implemented and pushed to:
https://github.com/CecilWesterhof/PythonLibrary/blob/master/filebasedMessages.py
Did some other optimisation's also. The function get_random_message
now calls get_indexed_message. Saves memory (on the old
implementation) and is more DRY.
I also enhanced get_nr_of_messages:
def get_nr_of_messages(message_filename):
i = -1
with open(expanduser(message_filename), 'r') as f:
for i, l in enumerate(f):
pass
return i + 1
Or can that be done better?
--
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
More information about the Python-list
mailing list