Bad file descriptor in Python 2.7

I upload a file with boto3 from AWS S3, this is the base JSON file.

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

I can open the JSON file, but when I go to the dump back to the same file after changing some values, I get 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()

Am I just using the wrong file mode, or am I doing it the wrong way?

+4
source share
1 answer

Two things. Its r+not rw, and if you want to overwrite previous data, you need to go back to the beginning of the file using fh.seek(0). Otherwise, the modified JSON string will be added.

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.

+6

All Articles