How do I download a file using urllib.request in Python 3?

后端 未结 2 1214
天涯浪人
天涯浪人 2021-02-20 18:57

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

相关标签:
2条回答
  • 2021-02-20 19:14

    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.

    It's just like reading a normal file (except for the syntax) and can be treated in a very similar way.

    0 讨论(0)
  • 2021-02-20 19:21

    change

    f.write(g)
    

    to

    f.write(g.read())
    
    0 讨论(0)
提交回复
热议问题