From 8505413b1bfa4592df2b09ac0a1841a9aecb9301 Mon Sep 17 00:00:00 2001 From: Subeen-Kim Date: Thu, 2 Nov 2017 00:33:10 -0400 Subject: [PATCH] learn about pickle --- counter.py | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/counter.py b/counter.py index 38ec816..c6661a5 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 +import os import sys +import pickle + +from os.path import exists from pickle import dump, load @@ -30,7 +33,25 @@ def update_counter(file_name, reset=False): >>> update_counter('blah2.txt') 2 """ - pass + if (not os.path.exists(file_name)) or reset: + new = open(file_name, 'wb') + pickle.dump(1, new) + new.close() + return 1 + + else: + checkfile = open(file_name, 'rb') + value = pickle.load(checkfile) + checkfile.close() + value = value + 1 + returnfile = open(file_name, 'wb') + pickle.dump(value, returnfile) + returnfile.close() + return value + +update_counter('blah2.txt') + + if __name__ == '__main__': if len(sys.argv) < 2: