Write contents of URL request to file

旧城冷巷雨未停 提交于 2019-12-06 02:18:43
tehsockz

Use urllib.urlretrieve (urllib.request.urlretrieve in Python 3).

In the console:

>>> import urllib
>>> urllib.urlretrieve('http://crypto-bot.hopto.org/server/list.php','test.txt') 
('test.txt', <httplib.HTTPMessage instance at 0x101338050>)

This results in a file, test.txt, being saving in the current working directory with the contents

ALF
AMC
ANC
ARG
...etc...

You need to read from the file object before writing to the file. Also you should the same object to both file and screen.

Do this:

import urllib.request

page = urllib.request.urlopen('http://crypto-bot.hopto.org/server/list.php')

f = open("test.txt", "w")
content = page.read()
f.write(content)
f.close()

print(content)

You're not reading the content from the urlopen file-like when you write to the file.

Also, shutil.copyfileobj().

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!