So I have the attached code, which works, MOSTLY
The source codes are attached (1 class file, and main file) to preserve spacing, etc. The main purpose of the code is to work with importing class...
when running the main file ...for example entering FOO (for name) BAR (for key) and MOO (for value) then [y] then FOOBAR0 (for filename)...this works fine.
Exit program
Rerun ...enter FOO (for name, again) BAR (for key) and MOO (for value) then [y] then FOOBAR0 (DON'T CHANGE FILENAME) and it yields an error. BUt if you go to terminal/command prompt and you will see that ALL data is in FOOBAR0.json
SO: my question is what makes json.load break when I use it for an already existing file - like the 2nd time I run the program
userdict0cl.py (Size: 486 bytes / Downloads: 658)
userdict0.py (Size: 544 bytes / Downloads: 593)
The source codes are attached (1 class file, and main file) to preserve spacing, etc. The main purpose of the code is to work with importing class...
when running the main file ...for example entering FOO (for name) BAR (for key) and MOO (for value) then [y] then FOOBAR0 (for filename)...this works fine.
Exit program
Rerun ...enter FOO (for name, again) BAR (for key) and MOO (for value) then [y] then FOOBAR0 (DON'T CHANGE FILENAME) and it yields an error. BUt if you go to terminal/command prompt and you will see that ALL data is in FOOBAR0.json
SO: my question is what makes json.load break when I use it for an already existing file - like the 2nd time I run the program
#userdict0.py import json from userdict0cl import D dname=str(input('select dictionary name: ')) dname= D() while True: keyy=str(input('enter key: ')) if keyy =='': break else: vall = str(input('enter value: ')) dname.fill(keyy,vall) dname.printall() saveyesno=str(input('want to save dictionary? [y/n] ')) if saveyesno =='n' or saveyesno =='': print('ok.') else: txt=str(input('enter file name. ')) txtfile = txt+'.json' print('you\'re file is: ' + txtfile) dname.write_items(txtfile) print('well done.') dname.print_json()
#userdict0cl.py import json class D(): def __init__(self): self._items = {} def fill(self,a,b): self.a = a self.b = b self._items[self.a]=self.b def printall(self): print(self._items) return self._items def write_items(self,filename): self._filename=filename with open(self._filename, 'a+') as f: json.dump(self._items, f) f.close() def print_json(self): with open(self._filename, 'r') as f: fn = json.load(f) #fn.seek(0) print(fn) f.close()
userdict0cl.py (Size: 486 bytes / Downloads: 658)
userdict0.py (Size: 544 bytes / Downloads: 593)