From 9d7840c26d175c4718eb3b2e58aba61e1d5364bf Mon Sep 17 00:00:00 2001 From: cedric kim Date: Sat, 12 Mar 2016 23:43:39 -0500 Subject: [PATCH] turning in pickle toolbox --- blah.txt | 3 +++ blah2.txt | 3 +++ counter.py | 22 +++++++++++++++------- test.txt | 3 +++ test.txt~ | 0 5 files changed, 24 insertions(+), 7 deletions(-) create mode 100644 blah.txt create mode 100644 blah2.txt create mode 100644 test.txt create mode 100644 test.txt~ diff --git a/blah.txt b/blah.txt new file mode 100644 index 0000000..4dd7b76 --- /dev/null +++ b/blah.txt @@ -0,0 +1,3 @@ +S'counter = 3' +p0 +. \ No newline at end of file diff --git a/blah2.txt b/blah2.txt new file mode 100644 index 0000000..eccf905 --- /dev/null +++ b/blah2.txt @@ -0,0 +1,3 @@ +S'counter = 2' +p0 +. \ No newline at end of file diff --git a/counter.py b/counter.py index 1e2fb56..345f613 100644 --- a/counter.py +++ b/counter.py @@ -1,4 +1,6 @@ -""" A program that stores and updates a counter using a Python pickle file""" +""" +Author = Cedric Kim +A program that stores and updates a counter using a Python pickle file""" from os.path import exists import sys @@ -29,11 +31,17 @@ def update_counter(file_name, reset=False): >>> update_counter('blah2.txt') 2 """ - pass + if not exists(file_name) or reset: ##if the file does not exist, or reset is true + counter_string = 'counter = 0' ##make a string with counter 0 + pickle.dump(counter_string, open(file_name, 'w')) ##dump the data into a the file + counter_string = pickle.load(open(file_name, 'r+')) ##open the file in r+ + counter_number = int(counter_string.lstrip('counter =')) ##find the value of the counter + updated_counter_string = 'counter = ' + str(counter_number+1) ##update the counter + pickle.dump(updated_counter_string, open(file_name, 'r+')) ##dump the new value in the file + return counter_number + 1 ##returns the value 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 + import pickle + import doctest + doctest.testmod() + print "new value is " + str(update_counter('test.txt')) \ No newline at end of file diff --git a/test.txt b/test.txt new file mode 100644 index 0000000..b78ae3f --- /dev/null +++ b/test.txt @@ -0,0 +1,3 @@ +S'counter = 34' +p0 +. \ No newline at end of file diff --git a/test.txt~ b/test.txt~ new file mode 100644 index 0000000..e69de29