From 9a4463a245da7666708c3969bc20b69a61aa94b2 Mon Sep 17 00:00:00 2001 From: Duncan Hall Date: Sat, 12 Mar 2016 14:55:31 -0500 Subject: [PATCH] done --- counter.py | 83 ++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 53 insertions(+), 30 deletions(-) diff --git a/counter.py b/counter.py index 1e2fb56..fefe1ec 100644 --- a/counter.py +++ b/counter.py @@ -4,36 +4,59 @@ import sys from pickle import dump, load + def update_counter(file_name, reset=False): - """ Updates a counter stored in the file 'file_name' - - A new counter will be created and initialized to 1 if none exists or if - the reset flag is True. - - If the counter already exists and reset is False, the counter's value will - be incremented. - - file_name: the file that stores the counter to be incremented. If the file - doesn't exist, a counter is created and initialized to 1. - reset: True if the counter in the file should be rest. - returns: the new counter value - - >>> update_counter('blah.txt',True) - 1 - >>> update_counter('blah.txt') - 2 - >>> update_counter('blah2.txt',True) - 1 - >>> update_counter('blah.txt') - 3 - >>> update_counter('blah2.txt') - 2 - """ - pass + """ Updates a counter stored in the file 'file_name' + + A new counter will be created and initialized to 1 if none exists or if + the reset flag is True. + + If the counter already exists and reset is False, the counter's value will + be incremented. + + file_name: the file that stores the counter to be incremented. If the file + doesn't exist, a counter is created and initialized to 1. + reset: True if the counter in the file should be rest. + returns: the new counter value + + >>> update_counter('blah.txt',True) + 1 + >>> update_counter('blah.txt') + 2 + >>> update_counter('blah2.txt',True) + 1 + >>> update_counter('blah.txt') + 3 + >>> update_counter('blah2.txt') + 2 + """ + if exists(file_name) and not reset: + f = open(file_name, 'r+') + count = load(f) + count += 1 + f.seek(0, 0) + dump(count, f) + f.close() + else: + count = 1 + f = open(file_name, 'w') + dump(count, f) + f.close() + + return count + if __name__ == '__main__': - if len(sys.argv) < 2: - import doctest - doctest.testmod() - else: - print "new value is " + str(update_counter(sys.argv[1])) \ No newline at end of file + if len(sys.argv) < 2: + import doctest + doctest.testmod() + doctest.run_docstring_examples( + update_counter, + globals(), + verbose=True, + name="Jus' Testin'" + ) + else: + print "new value is " + str(update_counter(sys.argv[1])) + +