我写了一个小脚本来生成一个json dict并将其插入到我正在使用的json文件的末尾。我认为我正在打开json文件并修改它的方式正在发生。
这是jist:
代码:
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'
该文件存在于该路径中,但是..
答案 0 :(得分:1)