【发布时间】:2021-03-06 20:02:39
【问题描述】:
Python 似乎不会写入我的第一个文件,但会写入第二个(也是最后一个)文件。
我正在编写一个不和谐的机器人,它接受公会 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
【问题讨论】:
-
我很乐意提供帮助。但是我不认为我有所有的拼图。你说它是
trying to load an empty json file。不应该吗?这是首先在其他地方填充的吗?请提供更多细节。您在discord_streambot.py中第 87 行的代码将有助于您(我相信)。很高兴为您提供帮助 -
json 文件不能为空,它应该在 writeToFile 字典中加载默认参数,如果有帮助,我将添加您请求的代码
-
在你打电话给
jsonInfo = json.load(File)之前你能print(File)吗?此外,将变量命名为首字母大写也不是好的编程习惯。它告诉人们变量是一个类。 -
我将在未来实施这种做法。输出如下:
<_io.TextIOWrapper name='402169002732027924.json' mode='w+' encoding='cp1252'>
标签: python json python-3.x discord.py