使用pyTelegramBotAPI发送.txt文件失败,报错400:文件不能为空
问题原因
你调用caps.read()之后,文件指针已经移动到了文件末尾,此时再将这个文件对象传给send_document,Telegram API读取到的内容就是空的,因此触发了file must be non-empty报错。
解决方法
以下三种方案都可以解决这个问题:
方案一:重置文件指针到开头
读取内容判断非空后,用seek(0)把文件指针移回文件开头,再发送文件:
@bot.message_handler(commands=["CAPTURED"]) def sendcaps(message): if "captured.txt" in os.listdir(): caps = open("captured.txt", "r") content = caps.read() if content != "": caps.seek(0) # 将文件指针重置到开头 bot.send_document(chat_id=message.chat.id, document=caps) else: bot.reply_to(message, "None") caps.close() # 手动关闭文件,避免资源泄漏
方案二:重新打开文件发送
判断内容非空后,重新打开一个新的文件对象用于发送:
@bot.message_handler(commands=["CAPTURED"]) def sendcaps(message): if "captured.txt" in os.listdir(): with open("captured.txt", "r") as f: content = f.read() if content != "": with open("captured.txt", "r") as caps: bot.send_document(chat_id=message.chat.id, document=caps) else: bot.reply_to(message, "None")
使用with语句会自动关闭文件,比手动关闭更安全。
方案三:用BytesIO包装内容发送
读取文件内容后,将其转为字节流对象发送,无需操作文件指针:
import io @bot.message_handler(commands=["CAPTURED"]) def sendcaps(message): if "captured.txt" in os.listdir(): with open("captured.txt", "rb") as f: content = f.read() if content: # 用BytesIO包装内容,同时指定发送后的文件名 bot.send_document(chat_id=message.chat.id, document=io.BytesIO(content), filename="captured.txt") else: bot.reply_to(message, "None")
内容的提问来源于stack exchange,提问作者user18932371
相关产品推荐
相关产品推荐

