From de81f5966dcaa5b92cc613543b1268be46f35f4b Mon Sep 17 00:00:00 2001 From: Lan Hui <1348141770@qq.com> Date: Tue, 3 Sep 2024 11:42:14 +0800 Subject: [PATCH] pickle_idea.py: Make funciton unfamiliar() more robust --- app/pickle_idea.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/app/pickle_idea.py b/app/pickle_idea.py index 45bd19a..d4fe991 100644 --- a/app/pickle_idea.py +++ b/app/pickle_idea.py @@ -6,6 +6,7 @@ # Purpose: dictionary & pickle as a simple means of database. # Task: incorporate the functions into wordfreqCMD.py such that it will also show cumulative frequency. +import os import pickle from datetime import datetime @@ -55,11 +56,13 @@ def save_frequency_to_pickle(d, pickle_fname): f.close() def unfamiliar(path,word): - f = open(path,"rb") - dic = pickle.load(f) - dic[word] += [datetime.now().strftime('%Y%m%d%H%M')] - fp = open(path,"wb") - pickle.dump(dic,fp) + if not os.path.exists(path): + return None + with open(path,"rb") as f: + dic = pickle.load(f) + dic[word] += [datetime.now().strftime('%Y%m%d%H%M')] + with open(path,"wb") as fp: + pickle.dump(dic,fp) def familiar(path,word): f = open(path,"rb")