【问题标题】:Not able to save the file in custom path directory using Python Telegram bot无法使用 Python Telegram bot 将文件保存在自定义路径目录中
【发布时间】:2021-04-24 08:55:31
【问题描述】:

我正在使用 Telegram 机器人下载文件,我当前的代码如下所示:

def file_handler(Update, context: CallbackContext):
    file = context.bot.getFile(Update.message.document.file_id)
    print("file_id: " + str(Update.message.document.file_id))
    file.download(custom_path='C:/Users/User/Desktop/python/projects/Telegram-Database/files')

def main():
    updater = Updater(token, use_context=True)
    dispatcher = updater.dispatcher
    dispatcher.add_handler(MessageHandler(Filters.document, file_handler))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

当我这样做时:

file.download()

它下载当前目录中的文件,但我想下载文件夹中的所有文件。所以我在这里查找了文档:https://python-telegram-bot.readthedocs.io/en/stable/telegram.file.html,实际上我可以设置自定义路径来下载该文件夹中的文件。但是,当我使用我当前的代码时,我得到一个权限错误:

    with open(filename, 'wb') as fobj:
PermissionError: [Errno 13] Permission denied: 'C:/Users/User/Desktop/python/projects/Telegram-Database/files'

我不知道为什么。我尝试重新创建文件夹并重新启动程序,但我总是遇到同样的错误。我在 Telegram 机器人中查找了这个特定的错误,但没有显示任何内容。你能帮忙吗?

【问题讨论】:

  • 不能写入文件夹,C:/Users/User/Desktop/python/projects/Telegram-Database/files 是文件夹,不是文件。
  • Ohhhhhhhhhhhhhhh,所以在这种情况下,我只是继续覆盖文件?
  • 尝试类似:file.download(custom_path='C:/Users/User/Desktop/python/projects/Telegram-Database/files/file1.txt')
  • 你能把它作为答案让我选择吗?

标签: python api telegram


【解决方案1】:

说明

您不能将文件夹视为文件,download 方法采用文件路径。如文档中所述:

下载此文件。默认情况下,文件以其原始文件名保存在当前工作目录中,如 Telegram 报告的那样。如果文件没有文件名,则文件 ID 将用作文件名。如果提供了custom_path,它将被保存到该路径。如果定义了 out,文件内容将使用out.write 方法保存到该对象。

代码

代码更改

您可以使用更改以下代码:

custom_path='C:/Users/User/Desktop/python/projects/Telegram-Database/files'

custom_path='C:/Users/User/Desktop/python/projects/Telegram-Database/files/file1.txt'

完整代码

def file_handler(Update, context: CallbackContext):
    file = context.bot.getFile(Update.message.document.file_id)
    print("file_id: " + str(Update.message.document.file_id))
    file.download(custom_path='C:/Users/User/Desktop/python/projects/Telegram-Database/files/file1.txt')

def main():
    updater = Updater(token, use_context=True)
    dispatcher = updater.dispatcher
    dispatcher.add_handler(MessageHandler(Filters.document, file_handler))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-14
    • 2018-09-24
    • 2013-12-05
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    相关资源
    最近更新 更多