I wrote a small script to generate a json dict and insert it into the end of a json file I'm using. I think there's something going on with the way I'm opening the json file and modifying it.
Here's the jist:
- It generates a json dict from raw_input
- It opens the json file and reads the lines, minus the last two containing "} ]"
- It writes the file back without the last two lines.
- Then, it writes the new dict entry with the closing "} ]"
The code:
JSON_PATH = "~/Desktop/python/custconn.json"
def main():
    # CLI Input
    group_in = raw_input("Group: ")
    name_in = raw_input("Name: ")
    nick_in = raw_input("Nick: ")
    host_in = raw_input("Host: ")
    user_in = raw_input("User: ")
    sshport_in = raw_input("SSH Port: ")
    httpport_in = raw_input("HTTP Port: ")
    # New server to add
    jdict = {
        "group": group_in,
        "name": name_in,
        "nick": nick_in,
        "host": host_in,
        "user": user_in,
        "sshport": sshport_in,
        "httpport": httpport_in
    }
    # Remove trailing "} ]" in json file
    with open(JSON_PATH, mode='r') as wf:
        lines = wf.readlines()
        lines = lines[:-2]
        wf.close()
    # Write change
    with open(JSON_PATH, mode='w') as wf:
        wf.writelines([item for item in lines])
        wf.close()
    # Write new server entry at the end
    with open(JSON_PATH, mode='a') as nf:
        nf.write("  },\n")
        nf.write("  {}\n".format(json.dumps(jdict, indent=4)))
        nf.write("]\n")
        nf.close()
The error:
Traceback (most recent call last):
  File "./jbuild.py", line 47, in <module>
    main()
  File "./jbuild.py", line 30, in main
    with open(JSON_PATH, mode='w') as wf:
IOError: [Errno 2] No such file or directory: '~/Desktop/python/custconn.json'
The file does exist at that path, however..
 
    