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..3315bd4 100644 --- a/counter.py +++ b/counter.py @@ -1,7 +1,10 @@ """ A program that stores and updates a counter using a Python pickle file""" -from os.path import exists +from os.path import exists +#Return True if path refers to an existing path. +#Returns False for broken symbolic links. import sys +import pickle from pickle import dump, load def update_counter(file_name, reset=False): @@ -29,11 +32,39 @@ def update_counter(file_name, reset=False): >>> update_counter('blah2.txt') 2 """ - pass + counter = 0 + + # If file dne or reset = True we will create counter starting at 1 + if exists(file_name) == False or reset == True: + f = open(file_name,'w') # f is now a file object ready to be written + counter = 1 # set counter ready to write to file + pickle.dump(counter,f) + return counter + f.close() + + # If file exist and reset = False we will add one to counter + elif exists(file_name) and reset == False: + f = open(file_name,'r+') # f is now a file object ready to be read and then written + counter = pickle.load(f) # load f as file already exists + f.seek(0,0) # moves pointer to start of file to write over previous content + counter += 1 # adds 1 to pre-existing counter + pickle.dump(counter,f) # update counter in f + return counter + f.close() + 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 + print "new value is " + str(update_counter(sys.argv[1])) # catches name variable + + + # I had a hard time with this, my main difficulty was in sorting out the order of operations to call + # 1) open/create file + # 2) if file contains content: load content with pickle + # 3) dump new content into file + # 4) return content & close file + + diff --git a/dogs b/dogs new file mode 100644 index 0000000..569369f --- /dev/null +++ b/dogs @@ -0,0 +1,2 @@ +I1 +. \ No newline at end of file diff --git a/pigs b/pigs new file mode 100644 index 0000000..569369f --- /dev/null +++ b/pigs @@ -0,0 +1,2 @@ +I1 +. \ No newline at end of file