Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
27 changes: 24 additions & 3 deletions counter.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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]))