json load problem - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: json load problem (/thread-7196.html) |
json load problem - mepyyeti - Dec-27-2017 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 #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()[attachment=332][attachment=331] RE: json load problem - buran - Dec-27-2017 Please, unless it is really big project, post your code in code tags, don't attach py files. See BBcode help for more info. This will make easier to answer and will attract more answers. I added these for your this time. Your problems comes every time when you use the same file name you append the json object to the file. As a result what you get is not A valid json file. e.g. after two 'runs' your json file will look like this you need to rethink your logic - e.g. load the json file and then append the new key-value pairs and then overwrite the existing file.there are other problems with your code 1. you overwrite dname immediately dname=str(input('select dictionary name: ')) dname= D()first it is a string, a "name" and immediately you use same variable for D instance, so you lost the name 2. It is better to implement __str__() method instead of print_json() see https://docs.python.org/3/reference/datamodel.html#basic-customization 3. unless you write to file, before you print, you will not have _filename property set and this will rise an error. i.e. if you try to print the json, before you write it to file. RE: json load problem - mepyyeti - Dec-27-2017 But I am writing (write_items()) first then printing (print_json()) I can remove dname as string. That's fairly easy. Can you offer a working example? I'm hopelessly lost ... RE: json load problem - Larz60+ - Dec-27-2017 Here's an example that creates two json files, and can read it back for a test This requires python 3.2 or later it will create two json files in a sub-directory named data EnigmaPaths.py from pathlib import Path class EnigmaPaths: def __init__(self): self.homepath = Path('.') self.datapath = self.homepath / 'data' self.imagepath = self.homepath / 'image' self.enigma_info = self.datapath / 'enigma_info.json' self.color_info = self.datapath / 'color_info.json' self.patchboard_image = self.imagepath / 'patchboard.ppm'InitializationData.py import EnigmaPaths import json class InitializationData: def __init__(self): self.epath = EnigmaPaths.EnigmaPaths() self.epath.datapath.mkdir(exist_ok=True) self.init_data = { 'rotor_info': { 'rotor1_info': { 'name': 'rotor1', 'cipher': 'EKMFLGDQVZNTOWYHXUSPAIBRCJ', 'notches': ['R'], }, 'rotor2_info': { 'name': 'rotor2', 'cipher': 'AJDKSIRUXBLHWTMCQGZNPYFVOE', 'notches': ['F'] }, 'rotor3_info': { 'name': 'rotor3', 'cipher': 'BDFHJLCPRTXVZNYEIWGAKMUSQO', 'notches': ['W'] }, 'rotor4_info': { 'name': 'rotor4', 'cipher': 'ESOVPZJAYQUIRHXLNFTGKDCMWB', 'notches': ['K'] }, 'rotor5_info': { 'name': 'rotor5', 'cipher': 'VZBRGITYUPSDNHLXAWMJQOFECK', 'notches': ['A'] }, # Rotor 6 - 8 available on Kriegsmarine M3 and M4 only 'rotor6_info': { 'name': 'rotor6', 'cipher': 'JPGVOUMFYQBENHZRDKASXLICTW', 'notches': ['A', 'N'] }, 'rotor7_info': { 'name': 'rotor7', 'cipher': 'NZJHGRCXMYSWBOUFAIVLPEKQDT', 'notches': ['A', 'N'] }, 'rotor8_info': { 'name': 'rotor8', 'cipher': 'FKQHTLXOCBJSPDZRAMEWNIUYGV', 'notches': ['A', 'N'] }, }, 'reflector_B': 'YRUHQSLDPXNGOKMIEBFZCWVJAT', 'reflector_C': 'FVPJIAOYEDRZXWGCTKUQSBNMHL', 'unencoded': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' } with self.epath.enigma_info.open('w') as f: json.dump(self.init_data, f) class Colors: ''' Colors from the the w3schools themes website: main: https://www.w3schools.com/w3css/w3css_colors.asp themes: https://www.w3schools.com/w3css/w3css_color_themes.asp and specifically portions of the w3-theme-black theme css for this theme can be found here: https://www.w3schools.com/lib/w3-theme-black.css ''' def __init__(self): self.epath = EnigmaPaths.EnigmaPaths() self.color_theme_black = { '.w3_theme_l5': { 'color': '#000', 'background-color': '#f0f0f0' }, '.w3-theme-l4': { 'color': '#000', 'background-color': '#cccccc' }, '.w3-theme-l3': { 'color': '#fff', 'background-color': '#999999' }, '.w3-theme-l2': { 'color': '#fff', 'background-color': '#666666' }, '.w3-theme-l1': { 'color': '#fff', 'background-color': '#333333' }, '.w3-theme-d1': { 'color': '#fff', 'background-color': '#000000' }, '.w3-theme-d2': { 'color': '#fff', 'background-color': '#000000' }, '.w3-theme-d3': { 'color': '#fff', 'background-color': '#000000' }, '.w3-theme-d4': { 'color': '#fff', 'background-color': '#000000' }, '.w3-theme-d5': { 'color': '#fff', 'background-color': '#000000' }, '.w3-theme-light': { 'color': '#000', 'background-color': '#f0f0f0' }, '.w3-theme-dark': { 'color': '#fff', 'background-color': '#000000' }, '.w3-theme-action': { 'color': '#fff', 'background-color': '#000000' }, '.w3-theme': { 'color': '#fff', 'background-color': '#000000' }, '.w3-text-theme': { 'color': '#000000' }, '.w3-border-theme': { 'border-color': '#000000' }, '.w3-hover-theme:hover': { 'color': '#fff', 'background-color': '#000000' }, '.w3-hover-text-theme': { 'color': '#000000' }, '.w3-hover-border-theme': { 'border-color': '#000000' } } with self.epath.color_info.open('w') as f: json.dump(self.color_theme_black, f) def test_read(self): with self.epath.color_info.open() as f: self.init_data = json.load(f) if __name__ == '__main__': InitializationData() Colors() RE: json load problem - mepyyeti - Dec-27-2017 hmmm. Your examples are totally above my head (I'm only learning python now on 3.6). I realize those are a peace of cake to you but I'm not there yet. I'm actually still trying to understand the point of if __name__ == '__main__': obj.method()maybe you're willing to run through that? I know the syntax but don;'t really see why I want apply it to my code. Never had a problem with obj.method() RE: json load problem - Larz60+ - Dec-28-2017 if __name__ == '__main__': obj.method()This allows the program to execute code differently, depending on how it's started To illustrate how this works, create the following two very short program: short.py def func1(): print('__name__: {}'.format(__name__)) func1()stillshort.py import short shortNow from a command line, first run: python short.pyresult: now run:python stillshort.pyresult: So, the if __name__ == '__main__':will only be true if the program was called directly. RE: json load problem - Larz60+ - Dec-28-2017 I never should have thrown that example at you without modification, I just grabbed it from a project. Here's a simpler example: import json def make_json(): init_data = { 'rotor1_info': { 'name': 'rotor1', 'cipher': 'EKMFLGDQVZNTOWYHXUSPAIBRCJ', 'notches': ['R'], } } with open('simple.json', 'w') as f: json.dump(init_data, f) def test_read(): mydata = {} with open('simple.json') as f: mydata = json.load(f) for key, value in mydata.items(): print('key: {}, Value: {}'.format(key, value)) if __name__ == '__main__': make_json() test_read()running get these results:
|