diff --git a/blah.txt b/blah.txt new file mode 100644 index 0000000..ba8c4c4 --- /dev/null +++ b/blah.txt @@ -0,0 +1,2 @@ +I3 +. \ No newline at end of file diff --git a/blah2.txt b/blah2.txt new file mode 100644 index 0000000..1cc9408 --- /dev/null +++ b/blah2.txt @@ -0,0 +1,2 @@ +I2 +. \ No newline at end of file diff --git a/counter.py b/counter.py index 1e2fb56..4386722 100644 --- a/counter.py +++ b/counter.py @@ -1,8 +1,8 @@ """ A program that stores and updates a counter using a Python pickle file""" -from os.path import exists +import os.path import sys -from pickle import dump, load +import pickle def update_counter(file_name, reset=False): """ Updates a counter stored in the file 'file_name' @@ -18,7 +18,7 @@ def update_counter(file_name, reset=False): reset: True if the counter in the file should be rest. returns: the new counter value - >>> update_counter('blah.txt',True) + >>> update_counter('blah.txt') 1 >>> update_counter('blah.txt') 2 @@ -29,11 +29,21 @@ def update_counter(file_name, reset=False): >>> update_counter('blah2.txt') 2 """ - pass + + if reset or not os.path.exists(file_name): + counter=1 + else: + f = open(file_name,'r') + counter = pickle.load(f) + counter+=1 + f = open(file_name,'w') + pickle.dump(counter,f) + return counter + if __name__ == '__main__': if len(sys.argv) < 2: import doctest - doctest.testmod() + doctest.testmod(verbose=True) else: - print "new value is " + str(update_counter(sys.argv[1])) \ No newline at end of file + print "new value is " + str(update_counter(sys.argv[1]))