Python 将变量保存到文本文件不起作用
我一直在尝试制作一个discord.py重写bot,它每天发送一条包含currentyear的消息(每天它应该上升一个),但是文本文件不会更新,它只是不断发布相同的变量Python 将变量保存到文本文件不起作用,python,discord.py,Python,Discord.py,我一直在尝试制作一个discord.py重写bot,它每天发送一条包含currentyear的消息(每天它应该上升一个),但是文本文件不会更新,它只是不断发布相同的变量 async def yearpost(): f = open("theyear.txt") currentyear = f.read() f.close message_channel = bot.get_channel(852955473802952774) await message_
async def yearpost():
f = open("theyear.txt")
currentyear = f.read()
f.close
message_channel = bot.get_channel(852955473802952774)
await message_channel.send(currentyear)
print(currentyear)
currentyear + str(1)
f = open("theyear.txt")
f.write(currentyear)
f.close
您需要打开文件进行写入
f = open("theyear.txt", "w")
有多种打字错误
f.close
必须是f.close()
,更重要的是,对于这里的问题,currentyear+str(1)
没有任何作用,因为您没有将结果赋回变量。如果我将其更改为currentyear+=1
,您希望currentyear+=1
而不是currentyear+str(1)
@Carcigenicate,则会导致bot吐出错误TypeError:只能将str(而不是“int”)连接到str
是,您需要先使用int
将currentyear
解析为整数,然后才能对其进行数学运算。@Carcigenicate抱歉,我现在可能非常愚蠢,但是,我该怎么做呢?currentyear=int(f.read())
。如果read
返回一个非数字,则此操作将失败,因此,如果有可能发生这种情况,您可能需要处理该问题(尽管可能永远不会发生这种情况)。然后,您需要在末尾使用f.write(str(currentyear))
将其转换回字符串。