Python不使用外部库下载文件
我有一个很大的Python脚本,我正在用pyinstaller把它变成一个exe文件。我需要下载一个XML文件,但我希望这个exe文件尽量小,因为它已经变得挺大的了。
在Python里有没有什么方法可以从网址获取文件?我找不到不需要外部库的办法。
1 个回答
5
你可以使用 urllib.urlretrieve() 这个方法,它可以把打开的网页保存到你指定的路径。
另外,你也可以用 urllib.urlopen() 打开网址,然后以二进制模式写入读取的文件:
import urllib
urllib.urlretrieve(url, destination_path) # First and short way
with open(destination_path, 'wb') as f: # Equivalent to the first, but longer
f.write(urllib.urlopen(url).read())