You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中无需重复开闭即可编辑并读取.json文件?

Python读写JSON文件:为什么不能一次性完成读写?

我想在Python里编辑JSON文件后直接读取,但没法用简洁的方式实现——必须先打开、写入、关闭,再重新打开、读取、关闭。

第一次尝试的代码

import json

passed_info = {
    "Tom": 14,
    "Sara": 12,
    "Maureen": 2
}

json_file = open("PathToMy.jsonFile", "r+")
json.dump(passed_info, json_file)

test = json.load(json_file)
print(test)

json_file.close()

运行报错信息

Traceback (most recent call last):
  File "PathToMyScript", line 12, in <module>
    test = json.load(json_file)
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python312\Lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
           ^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python312\Lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python312\Lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python312\Lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

分开开闭文件的可行代码

import json

passed_info = {
    "Tom": 14,
    "Sara": 12,
    "Maureen": 2
}

json_file = open("PathToMy.jsonFile", "r+")
json.dump(passed_info, json_file)

json_file.close()

json_file = open("PathToMy.jsonFile", "r+")
test = json.load(json_file)
print(test)

json_file.close()

输出结果

{'Tom': 14, 'Sara': 12, 'Maureen': 2}

为什么必须重复开闭文件?

核心原因是文件指针的位置:
当你用json.dump把数据写入文件后,文件内部的读写指针会停在文件的末尾。这时候调用json.load,会从当前指针位置开始读取——也就是从文件末尾读,自然读不到任何有效内容,所以JSON解码器会抛出"Expecting value"的错误(因为没有读到可解析的JSON数据)。

而关闭再重新打开文件时,文件指针会自动重置到文件开头,这时候json.load就能正常读取到刚写入的内容了。


更简洁的解决方案

不需要重复开闭文件,有两种更优雅的方式:

1. 写入后重置文件指针

用seek(0)将文件指针移回开头,就能在同一个文件句柄下完成读写:

import json

passed_info = {
    "Tom": 14,
    "Sara": 12,
    "Maureen": 2
}

# 使用with语句自动管理文件,无需手动close
with open("PathToMy.jsonFile", "r+") as json_file:
    json.dump(passed_info, json_file)
    json_file.seek(0)  # 将指针移回文件开头
    test = json.load(json_file)
    print(test)

2. 用两个with块分离读写(更清晰)

如果觉得指针操作麻烦,也可以用两个独立的with块分别处理写入和读取,代码更直观,同时自动关闭文件:

import json

passed_info = {
    "Tom": 14,
    "Sara": 12,
    "Maureen": 2
}

# 写入文件(w模式会自动创建文件,若存在则覆盖)
with open("PathToMy.jsonFile", "w") as json_file:
    json.dump(passed_info, json_file)

# 读取文件
with open("PathToMy.jsonFile", "r") as json_file:
    test = json.load(json_file)
    print(test)

是否应该继续用重复开闭的写法?

不建议。原因有两点:

  1. 手动调用close()容易遗漏,导致文件资源泄漏;
  2. 代码冗余,用with语句或指针重置的方式更简洁、安全,也符合Python的最佳实践。

内容的提问来源于stack exchange,提问作者BaromaOback

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 03:34:58