Why doesn't this work? - 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: Why doesn't this work? (/thread-1120.html) |
Why doesn't this work? - PickyBiker - Dec-05-2016 I am learning python and having a problem with reading .json files. There are 2 reads, one for status.json and the other for schedue.json The code shown below works just fine, unless you un-comment the last two lines. Why is the second read causing errors? import os, sys, time, datetime, json def WriteStatusJSON(control, pump, zones, ontime): update = {"control": control, "pump": pump, "zones": zones, "ontime": ontime} with open('status.json', 'w') as outfile: json.dump(update, outfile) outfile.close() def ReadStatusJSON(): with open('status.json') as infile: data = json.load(infile) infile.close() control = data["control"] zones = data["zones"] pump = data["pump"] ontime = data["ontime"] if ontime != None: hour = ontime[0] minute = ontime[1] return data def WriteScheduleJSON(weekdays, ontime, zones): update = {"weekdays": weekdays, "ontime": ontime, "zones": zones} with open('schedule.json', 'w') as outfile: json.dump(update, outfile) outfile.close() def ReadScheduleJSON(): with open('schedule.json') as infile: data = json.load(infile) infile.close() weekdays = data["weekdays"] ontime = data["ontime"] hour = ontime[0] minute = ontime[1] zones = data["zones"] return data status = ReadStatusJSON() print(status['control']) #schedule = ReadScheduleJSON() #print(schedule['weekdays'])Here is the status.json file contents: Quote:{"control": "Start", "zones": [[5, 15]], "pump": false, "ontime": [13, 25]} Here is the schedule.json file contents: Quote:{"zones": [[1, 10], [2, 10], [3, 10], [4, 10], [5, 10], [6, 10]], "weekdays": [1, 3, 5], "ontime": [5, 30]} RE: Why doesn't this work? - nilamo - Dec-05-2016 What's the error? Also, why are you closing your files? with does that for you. If you want to close things yourself, don't use with :p
RE: Why doesn't this work? - PickyBiker - Dec-05-2016 I didn't know with closed the files... I'll change that, THANKS! Here are the errors:
RE: Why doesn't this work? - PickyBiker - Dec-06-2016 I opened schedule.json with a hex editor and found there were 3 unprintable characters in the file before the opening brace '{'. Once removed, the file works just fine. Now to find out why those get in there, but that's a different problem. Case closed. |