OSError:[Errno 9]由于尝试写入json文件而导致文件描述符错误

2024-04-28 21:38:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个范围为calculate的程序,并在JSON文件中写入一些covid-19统计信息 我试着写下:

import json
from json import JSONEncoder

f = open("contagi.json","a")
class contagi():
    def __init__(self , giorno , mese , anno , contagi_del_giorno):
        self.giorno = giorno
        self.mese = mese
        self.anno = anno
        self.x_contagi = contagi_del_giorno
    def toJSON(self):
        return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)

y = contagi(18,10,2020,10095)

print(y.toJSON())

f.write(y.toJSON())
f.close()

但它得到了这个错误:

>python contagi.py


{
    "anno": 2020,
    "giorno": 18,
    "mese": 10,
    "x_contagi": 10095
}
OSError: [Errno 9] Bad file descriptor

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\giuse\Documents\json + python\contagi.py", line 20, in <module>
    f.close()
OSError: [Errno 9] Bad file descriptor

Tags: pyimportselfjsonclosedefbaddel