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