Step further with filebasedMessages
Cecil Westerhof
Cecil at decebal.nl
Tue May 5 04:52:54 EDT 2015
I now defined get_message_slice:
### Add step
def get_message_slice(message_filename, start, end):
"""
Get a slice of messages, where 0 is the first message
Works with negative indexes
The values can be ascending and descending
"""
message_list = []
real_file = expanduser(message_filename)
nr_of_messages = get_nr_of_messages(real_file)
if start < 0:
start += nr_of_messages
if end < 0:
end += nr_of_messages
assert (start >= 0) and (start < nr_of_messages)
assert (end >= 0) and (end < nr_of_messages)
if start > end:
tmp = start
start = end
end = tmp
need_reverse = True
else:
need_reverse = False
with open(real_file, 'r') as f:
for message in islice(f, start, end + 1):
message_list.append(message.rstrip())
if need_reverse:
message_list.reverse()
return message_list
Is that a good way?
I also had:
def get_indexed_message(message_filename, index):
"""
Get index message from a file, where 0 gets the first message
A negative index gets messages indexed from the end of the file
Use get_nr_of_messages to get the number of messages in the file
"""
real_file = expanduser(message_filename)
nr_of_messages = get_nr_of_messages(real_file)
if index < 0:
index += nr_of_messages
assert (index >= 0) and (index < nr_of_messages)
with open(real_file, 'r') as f:
[line] = islice(f, index, index + 1)
return line.rstrip()
But changed it to:
def get_indexed_message(message_filename, index):
"""
Get index message from a file, where 0 gets the first message
A negative index gets messages indexed from the end of the file
Use get_nr_of_messages to get the number of messages in the file
"""
return get_message_slice(message_filename, index, index)[0]
Is that acceptable? I am a proponent of DRY.
Or should I at least keep the assert in it?
--
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
More information about the Python-list
mailing list