Python似乎并没有写入我的第一个文件,而是写入了第二个(也是最后一个)文件
我正在写一个discord机器人,它接受公会ID并使用它们作为文件名,对于每个公会,我想要一个包含特定公会变量的json文件
一切都很好,直到我找不到任何可能的解决方案:
Task exception was never retrieved
future: <Task finished name='Task-13' coro=<twitchGet() done, defined at C:\Users\Pedro\Desktop\Python\discord_streambot.py:82> exception=JSONDecodeError('Expecting value: line 1 column 1 (char 0)')>
Traceback (most recent call last):
File "C:\Users\Pedro\Desktop\Python\discord_streambot.py", line 87, in twitchGet
values = await getJsonValues(guild.id)
File "C:\Users\Pedro\Desktop\Python\discord_streambot.py", line 79, in getJsonValues
jsonInfo = json.load(File)
File "C:\Users\Pedro\AppData\Local\Programs\Python\Python39-32\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\Pedro\AppData\Local\Programs\Python\Python39-32\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\Pedro\AppData\Local\Programs\Python\Python39-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Pedro\AppData\Local\Programs\Python\Python39-32\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
现在,幸运的是,我知道如何读取,并且我可以确定问题在于json.load()函数试图加载一个空的json文件,但是我的json编写函数似乎没有任何问题,是否有人知道该函数的错误或其他编写方法?我重复一遍,函数写入第二个(现在是最后一个)文件,但不是第一个
def createDefaultFile(id: int):
writeToFile = {
'delay' : TIMEDELAY,
'streamers' : [],
'textchannel' : None,
}
file = Path(str(id)+'.json')
if file.is_file():
print('File Exists \n')
else:
print('Creating File \n')
open(str(id)+'.json','a').close()
with open(str(id) + '.json', 'w', encoding ='utf8') as json_file:
json.dump(writeToFile, json_file)
编辑: 根据要求,discord_streambot.py的第87行
#Check if there are streamers set
count = 0
for guild in bot.guilds:
values = await getJsonValues(guild.id)
for streamer in values['streamers']:
count += 1
getJsonValues函数:
async def getJsonValues(id: int):
try:
File = open(str(id)+'.json','w+')
except IOError:
print('Cannot open file')
return None
jsonInfo = json.load(File)
return jsonInfo
请打印您的JSON文件的内容,我不能不看就确定,但是我相信您的问题是JSON文件是空的。请先将其写入JSON文件:
{}
然后再试一次。如果它不起作用,那么打印JSONs内容并回复这个答案,这样我可以进一步帮助您我遇到的问题是行中的函数getJsonValues
很明显,“w+”会弄乱文件,每次我运行函数时都会将其变为空,并将其更改为“r”,因为“w+”不是必需的,所以它解决了这个问题。谢谢你
相关问题 更多 >
编程相关推荐