【发布时间】:2019-11-04 21:23:10
【问题描述】:
我会这样做:
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'
确实,我没有事先在Desktop 中创建data.json 文件,但我认为这是我上面的代码应该做的。
我该怎么做?
【问题讨论】:
-
~实际上并不是您要使用的路径名中的字符。 Shell 将其解释为对您的主目录的引用,但 Shell 并未处理此代码。您可以使用os.path.expanduser()在 Python 中获得相同的解释。