簡體   English   中英

Python 2.7中的錯誤文件描述符

[英]Bad file descriptor in Python 2.7

我正在從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是。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM