json.dump 未写入文件

use*_*511 2 python file-io json python-3.x

我将dump这样的函数与名为 test.py 的文件一起使用:

import json

li = [2, 5]
test = open('test.json', 'w')
json.dump(li, test)
Run Code Online (Sandbox Code Playgroud)

但代码运行后并没有写入 JSON 文件。为什么是这样?正确的使用方法是什么json.dump

Mad*_*ist 7

更改通常以块的形式写入磁盘,通常约为 2 或 4KiB 左右。由于您的测试文件很小,因此在您关闭文件、REPL 或您的脚本终止之前,更改不会从 REPL 中刷新。

文件有一个close可以用来显式关闭的方法。然而,在 python 中处理文件的惯用方法是使用块with

import json

li = [2, 5]
with open('test.json', 'w') as test:
    json.dump(li, test)
Run Code Online (Sandbox Code Playgroud)

这大致相当于

li = [2, 5]
test = open('test.json', 'w')
try:
    json.dump(li, test)
finally:
    test.close()
Run Code Online (Sandbox Code Playgroud)