【问题标题】:Bad file descriptor in Python 2.7Python 2.7 中的错误文件描述符
【发布时间】:2016-09-09 21:05:24
【问题描述】:

我正在从 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()

我只是使用了错误的文件模式还是我做错了?

【问题讨论】:

  • 打开文件进行读取,读取您的信息,进行更改,然后打开文件进行写入,然后转储。
  • rw 不存在。你正在寻找r+

标签: python json file


【解决方案1】:

两件事。它的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的用途。

【讨论】:

    猜你喜欢
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多