我做了这样的事:
import json
data = { "id": 1 }
with open('~/Desktop/data.json', 'w') as f:
json.dump(data, f)但我知道这个错误:
FileNotFoundError: [Errno 2] No such file or directory: '...Desktop/data.json'事实上,我并没有预先在data.json中创建Desktop文件,但我认为这正是我上面的代码应该做的。
我该怎么做?
发布于 2019-11-04 21:32:31
Python无法在文件路径中处理~,因为~是巴什特征。您可以使用os模块获得主目录路径:
import os
print(os.getenv('HOME'))发布于 2019-11-04 22:15:02
要添加到前面的答案:您可以使用"w+“来让python在不存在的情况下创建文件。
发布于 2019-11-04 21:34:06
就像@jasonharper提到的:
import json
data = { "id": 1 }
with open(os.path.expanduser("~")+'/Desktop/data.json', 'w') as f:
json.dump(data, f)https://stackoverflow.com/questions/58701260
复制相似问题