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

为何os.open()返回整数而非文件对象?json模块报错解决

解决json模块与os.open配合的报错问题

为什么会出现AttributeError?

os.open()返回的是整数类型的文件描述符,而json.dump()/json.load()要求传入的是支持.write()/.read()方法的Python文件对象,直接传入文件描述符自然会触发报错。

解决方案

方案1:使用Python内置的open()函数(推荐)

这是最简洁安全的方式,直接返回符合要求的文件对象,配合with语句还能自动管理文件关闭:

写入JSON:

import json

# w+模式:读写模式,文件不存在则创建,存在则清空
with open("Some_file.json", "w+") as file:
    data = {"something": "something"}
    json.dump(data, file)

读取JSON:

import json

# r模式:只读模式
with open("Some_file.json", "r") as file:
    data = json.load(file)

方案2:用os.fdopen()转换文件描述符(如果必须用os.open)

如果因为特殊需求必须使用os.open(),可以通过os.fdopen()将整数文件描述符转换为Python文件对象:

写入JSON:

import os
import json

# 加上os.O_CREAT确保文件不存在时创建
fd = os.open("Some_file.json", flags=os.RDWR | os.TRUNC | os.O_CREAT)
with os.fdopen(fd, "w") as file:
    data = {"something": "something"}
    json.dump(data, file)

读取JSON:

import os
import json

fd = os.open("Some_file.json", flags=os.RDONLY)
with os.fdopen(fd, "r") as file:
    data = json.load(file)

关于JSONDecodeError的说明

你遇到的JSONDecodeError大概率是因为读取的文件内容为空(比如之前用os.TRUNC清空了文件但未写入内容),或者文件指针位置不对(写入后未移动到文件开头就读取)。用上面两种正确方式处理文件对象后,这类问题会自然避免。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 03:22:34