![](/img/trans.png)
[英]Copying the first line in the .txt file and writing it to the last line Python
[英]Python writing to the last file but not the first one
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
请打印您的 JSON 文件的内容,如果不查看我无法确定,但是我相信您的问题是 JSON 文件为空。 请先在 JSON 文件中写入: {}
然后再试一次。 如果它不起作用,则打印 JSON 内容并回复此答案,以便我可以进一步帮助您。
我遇到的问题是在函数 getJsonValues 中
File = open(str(id)+'.json','w+')
显然,'w+' 弄乱了文件,每次我运行该函数时都将其清空,将其更改为 'r',因为 'w+' 不是必需的,它解决了它。 不管怎么说,多谢拉
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.