为何重启Discord Bot程序后TXT日志文件内容自动清空?
问题原因
你用"w"模式打开日志文件,这个模式的行为是清空文件原有内容后写入新数据,所以每次执行ping命令时,之前的日志都会被覆盖,重启后第一次执行命令自然就看不到之前的日志了。手动调用close()不影响这个问题,核心是打开模式的选择错误。
解决方法
把文件打开模式从"w"改成"a"(追加模式),这个模式会在文件末尾添加新内容,不会覆盖原有日志。同时推荐用with语句管理文件操作,它会自动处理文件关闭,比手动调用close()更可靠。
修改后的ping命令代码:
@bot.command() async def ping(a): await a.send('Pong!') # 用追加模式打开文件,with语句自动管理关闭 with open('C:\\Users\\pooki\\OneDrive\\Bureau\\Codes\\GBot 4\\logs.txt', "a", encoding="utf-8") as logs: logs.write(f'{date.today().strftime("%d/%m/%Y")} at {datetime.now().strftime("%H:%M:%S")}:@{a.message.author.name} said ping.\n')
另外可以简化日期时间的写法,直接用datetime.now()同时获取日期和时间:
@bot.command() async def ping(a): await a.send('Pong!') now = datetime.now() with open('C:\\Users\\pooki\\OneDrive\\Bureau\\Codes\\GBot 4\\logs.txt', "a", encoding="utf-8") as logs: logs.write(f'{now.strftime("%d/%m/%Y at %H:%M:%S")}: @{a.message.author.name} said ping.\n')
修改后,每次执行ping命令都会在日志文件末尾追加新记录,重启程序后之前的日志会被保留。
内容的提问来源于stack exchange,提问作者3pm
相关产品推荐
相关产品推荐

