python - Python 2.7 中的错误文件描述符

标签 python json file

我正在从 AWS S3 下载一个带有 boto3 的文件,它是一个基本的 JSON 文件。

{
    "Counter": 0,
    "NumOfReset": 0,
    "Highest": 0
}

我可以打开 JSON 文件,但是当我在更改一些值后将其转储回同一个文件时,我得到了 IOError: [Errno 9] Bad file descriptor

with open("/tmp/data.json", "rw") as fh:
    data = json.load(fh)
    i = data["Counter"]
    i = i + 1
    if i >= data["Highest"]:
        data["Highest"] = i
    json.dump(data, fh)
    fh.close()

我只是使用了错误的文件模式还是我这样做不正确?

最佳答案

两件事。它的r+不是rw,如果要覆盖之前的数据,需要回到文件开头,使用fh.seek(0) 。否则,将附加更改的 JSON 字符串。

with open("/tmp/data.json", "r+") as fh:
    data = json.load(fh)
    i = data["Counter"]
    i = i + 1
    if i >= data["Highest"]:
        data["Highest"] = i

    fh.seek(0)
    json.dump(data, fh)
    fh.close()

但这可能只会部分覆盖数据。因此,使用 w 关闭并重新打开文件可能是一个更好的主意。

with open("/tmp/data.json", "r") as fh:
    data = json.load(fh)

i = data["Counter"]
i = i + 1
if i >= data["Highest"]:
    data["Highest"] = i

with open("/tmp/data.json", "w") as fh:
    json.dump(data, fh)
    fh.close()

不需要 fh.close(),这就是 with .. as 的用途。

关于python - Python 2.7 中的错误文件描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37213866/

相关文章:

python - 为什么基类在多重继承中不起作用?

php - Laravel Eloquent 排序查询

python - 循环遍历目录以查找匹配的文件

java - 从 HashSet 中的 md5 列表中删除文件

python - 将 ARMA() 模型拟合到假定平稳的时间序列时的平稳性问题

python - 使用 Python 引发异常时回滚操作的最佳方法

python - 将 CSV 转置为 JSON

ruby-on-rails - Rails Controller 丢失 JSON 字符串中的换行符

file - 使用进度条提取存档 - 可变借用错误

python - 如何在 Python 中处理传入的 PubSub 消息?