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
2 changes: 2 additions & 0 deletions blah.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
I3
.
2 changes: 2 additions & 0 deletions blah2.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
I2
.
37 changes: 34 additions & 3 deletions counter.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down Expand Up @@ -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]))
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


2 changes: 2 additions & 0 deletions dogs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
I1
.
2 changes: 2 additions & 0 deletions pigs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
I1
.