So, I'm messing around with urllib.request
in Python 3 and am wondering how to write the result of getting an internet file to a file on the local machine. I tried this:
我在玩小熊星座。在Python 3中请求,我想知道如何将一个internet文件的结果写入本地机器上的文件。我试着这样的:
g = urllib.request.urlopen('http://media-mcw.cursecdn.com/3/3f/Beta.png')
with open('test.png', 'b+w') as f:
f.write(g)
But I got this error:
但我犯了一个错误:
TypeError: 'HTTPResponse' does not support the buffer interface
What am I doing wrong?
我做错了什么?
NOTE: I have seen this question, but it's related to Python 2's urllib2
which was overhauled in Python 3.
注意:我看到过这个问题,但是它与Python 2的urllib2有关,后者在Python 3中被彻底检查过。
2 个解决方案
#1
8
change
改变
f.write(g)
to
来
f.write(g.read())
#2
0
An easier way I think (also you can do it in two lines) is to use:
我认为一个更简单的方法(也可以用两行)是:
import urllib.request
urllib.request.urlretrieve('http://media-mcw.cursecdn.com/3/3f/Beta.png', 'test.png')
As for the method you have used. When you use g = urllib.request.urlopen('http://media-mcw.cursecdn.com/3/3f/Beta.png')
you are just fetching the file. You must use g.read()
, g.readlines()
or g.readline()
to read it it.
至于你用过的方法。当您使用g = urllib.request.urlopen('http://media-mcw.cursecdn.com/3/3f/Beta.png')时,您只是在获取文件。您必须使用g.read()、g.readlines()或g.readline()来读取它。
It's just like reading a normal file (except for the syntax) and can be treated in a very similar way.
这就像读取一个普通的文件(除了语法),并且可以以非常相似的方式进行处理。
#1
8
change
改变
f.write(g)
to
来
f.write(g.read())
#2
0
An easier way I think (also you can do it in two lines) is to use:
我认为一个更简单的方法(也可以用两行)是:
import urllib.request
urllib.request.urlretrieve('http://media-mcw.cursecdn.com/3/3f/Beta.png', 'test.png')
As for the method you have used. When you use g = urllib.request.urlopen('http://media-mcw.cursecdn.com/3/3f/Beta.png')
you are just fetching the file. You must use g.read()
, g.readlines()
or g.readline()
to read it it.
至于你用过的方法。当您使用g = urllib.request.urlopen('http://media-mcw.cursecdn.com/3/3f/Beta.png')时,您只是在获取文件。您必须使用g.read()、g.readlines()或g.readline()来读取它。
It's just like reading a normal file (except for the syntax) and can be treated in a very similar way.
这就像读取一个普通的文件(除了语法),并且可以以非常相似的方式进行处理。