Search code examples
pythonjsonioerror

Python: IOError: [Errno 2] No such file or directory: - But file exists


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:

  1. It generates a json dict from raw_input
  2. It opens the json file and reads the lines, minus the last two containing "} ]"
  3. It writes the file back without the last two lines.
  4. 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..


Solution

  • You need os.path.expanduser:

    On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.

    import os
    os.path.expanduser(path)