Python:IOError:[Errno 2]没有这样的文件或目录: - 但文件存在

时间:2015-02-03 19:45:58

标签: python json ioerror

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

这是jist:

  1. 它从raw_input
  2. 生成一个json dict
  3. 打开json文件并读取行,减去包含“}]”
  4. 的最后两行
  5. 它将文件写回而没有最后两行。
  6. 然后,它用关闭“}]”
  7. 写入新的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'
    

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

1 个答案:

答案 0 :(得分:1)

您需要os.path.expanduser

在Unix和Windows上,返回参数的初始组件〜或〜用户替换为该用户的主目录。

import os
os.path.expanduser(path)