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

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

我写了一个小脚本来生成 json 字典并将其插入到我正在使用的 json 文件的末尾。我认为我打开 json 文件并修改它的方式有问题。

要点如下:

  1. 它从 raw_input
  2. 生成一个 json 字典
  3. 它打开 json 文件并读取行,减去包含“} ]”的最后两行
  4. 它在没有最后两行的情况下写回文件。
  5. 然后,它写入新的 dict 条目以结束“}]”

代码:

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()

错误:

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'

文件确实存在于该路径,但是..

你需要os.path.expanduser:

在 Unix 和 Windows 上,return 参数的初始部分 ~ 或 ~user 替换为该用户的主目录。

import os
os.path.expanduser(path)