diff --git a/README.md b/README.md index 2260597..4e48cce 100644 --- a/README.md +++ b/README.md @@ -2,3 +2,7 @@ Pickling Project Toolbox starter code Full instructions at https://sites.google.com/site/sd16spring/home/project-toolbox/pickling + +This program stores and update a counter. The fucntion update_counter takes a file name and reset indication (boolean True or Flase) as inputs. If the file does not exist, it will be created and the counter will be initialized to 1. If the file exists and the reset is set to True, the counter will be reset to 1. If the file exist and the reset is False, the counter will increment by 1. + +When the code is called in terminal, it runs its doctests and shows the results. If you wish to run this code, add a line at the end that calls update_counter with your desired file and reset. diff --git a/counter.py b/counter.py index 1e2fb56..0c08e77 100644 --- a/counter.py +++ b/counter.py @@ -1,4 +1,7 @@ -""" A program that stores and updates a counter using a Python pickle file""" +""" A program that stores and updates a counter using a Python pickle file + + +@AUTHOR: REBECCA PATTERSON 03-10-16""" from os.path import exists import sys @@ -29,11 +32,29 @@ def update_counter(file_name, reset=False): >>> update_counter('blah2.txt') 2 """ - pass + if exists(file_name) and reset==False: + #open the file for reading and plus writing into variable name + f= open(file_name, 'r+') + #load the contents of the file into another variable + count= load(f) + count+=1 + #moves the handle back to the beginning so the dump will + #overwrite the old contents + f.seek(0,0) + dump(count,f) + f.close() + return count + else: + #open a new/overwrite a file for writing into a variable name + f= open(file_name,'w') + count= 1 + dump(count, f) + f.close() + return count 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