Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completed the given function #40

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
72 changes: 46 additions & 26 deletions counter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,54 @@

from os.path import exists
import sys
from pickle import dump, load
import pickle

def update_counter(file_name, reset=False):
""" Updates a counter stored in the file 'file_name'

A new counter will be created and initialized to 1 if none exists or if
the reset flag is True.

If the counter already exists and reset is False, the counter's value will
be incremented.

file_name: the file that stores the counter to be incremented. If the file
doesn't exist, a counter is created and initialized to 1.
reset: True if the counter in the file should be rest.
returns: the new counter value

>>> update_counter('blah.txt',True)
1
>>> update_counter('blah.txt')
2
>>> update_counter('blah2.txt',True)
1
>>> update_counter('blah.txt')
3
>>> update_counter('blah2.txt')
2
"""
pass
""" Updates a counter stored in the file 'file_name'

A new counter will be created and initialized to 1 if none exists or if
the reset flag is True.

If the counter already exists and reset is False, the counter's value will
be incremented.

file_name: the file that stores the counter to be incremented. If the file
doesn't exist, a counter is created and initialized to 1.
reset: True if the counter in the file should be rest.
returns: the new counter value

>>> update_counter('blah.txt',True)
1
>>> update_counter('blah.txt')
2
>>> update_counter('blah2.txt',True)
1
>>> update_counter('blah.txt')
3
>>> update_counter('blah2.txt')
2
"""
if not exists(file_name) or reset:
#initialize to 1
f = open(file_name, 'w')
d = pickle.dump(1, f)
f.close()

#check that it worked
check = open(file_name, 'r')
initialized_value = pickle.load(check)
return initialized_value
else:
#open and find the value
f = open(file_name, 'r')
value = pickle.load(f) + 1
f.close()

#open and write a new value
f = open(file_name, 'w')
d = pickle.dump(value, f)
f.close()
return value

if __name__ == '__main__':
if len(sys.argv) < 2:
Expand Down