提供由urlopen()或request.get()创建的类似文件的对象的文件名
发布于 2021-01-29 16:07:32
关注者
0
被浏览
80
1 个回答
-
您将提供文件名作为对象的
.name
属性。open()
使用.name属性打开文件。>>>local_file = open("file.txt") >>>local_file <open file 'file.txt', mode 'r' at ADDRESS> >>>local_file.name 'file.txt'
在没有打开URL的地方。这就是为什么文档专门提到了这一点。
>>>import urllib >>>url_file = urllib.open("http://example.com/index.hmtl") >>>url_file <addinfourl at 44 whose fp = <open file 'nul', mode 'rb' at ADDRESS>> >>>url_file.name AttributeError: addinfourl instance has no attribute 'name'
对于您的情况,您将需要创建类似文件的对象,并为其赋予一个
.name
属性:res = requests.get(some_url) the_file = io.BytesIO(res.content) the_file.name = 'file.image' tbot.sendPhoto( messenger_id, the_file )