You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用py-telegram-bot-api发送文档:f.read()后文件发送异常问题

py-telegram-bot-api发送文件的空文件检测问题

f.read()的作用

f.read()会一次性读取文件指针当前位置到文件末尾的全部内容,执行完这个操作后,文件指针会停在文件末尾。这时候如果再把这个文件对象传给send_document,因为指针已经在末尾,读取不到任何内容,就会被Telegram判定为空文件。

解决办法

有三种可行的处理方式,你可以根据需求选择:

方式一:重置文件指针位置

读取内容检查完后,用f.seek(0)把文件指针移回开头,这样send_document就能正常读取文件内容了:

with open(path, "r", encoding="utf-8") as f:
    text = f.read().strip()
    if not text:
       bot.send_message(chat_id, "File is empty")
       return
    f.seek(0)  # 将文件指针重置到文件开头
    bot.send_document(chat_id, f)

方式二:直接检查文件大小

不用读取文件内容,直接通过文件大小判断是否为空,这种方式更高效,尤其适合大文件:

import os

if os.path.getsize(path) == 0:
    bot.send_message(chat_id, "File is empty")
else:
    with open(path, "r", encoding="utf-8") as f:
        bot.send_document(chat_id, f)

方式三:精准捕获API异常

其实你可以直接捕获ApiTelegramException,通过错误码和描述判断是否是空文件问题,这样省去预检查步骤:

from telebot.apihelper import ApiTelegramException

try:
    with open(path, "r", encoding="utf-8") as f:
        bot.send_document(chat_id, f)
except ApiTelegramException as e:
    if e.error_code == 400 and "file must be non-empty" in e.description:
        bot.send_message(chat_id, "File is empty")
    else:
        # 其他API异常按原有逻辑处理
        raise e

内容的提问来源于stack exchange,提问作者user18196171

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 23:18:31