Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将变量保存到文本文件不起作用_Python_Discord.py - Fatal编程技术网

Python 将变量保存到文本文件不起作用

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_

我一直在尝试制作一个discord.py重写bot,它每天发送一条包含currentyear的消息(每天它应该上升一个),但是文本文件不会更新,它只是不断发布相同的变量

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))
将其转换回字符串。