【问题标题】:Python download file without external library没有外部库的Python下载文件
【发布时间】:2014-03-10 17:03:33
【问题描述】:

我有一个非常大的 Python 脚本,我正在使用 pyinstaller 创建一个 exe。我需要下载一个 XML 文件,但希望 exe 尽可能小,因为它已经变得相当大了。

Python 中是否有从 URL 获取文件的方法?如果没有外部库,我什么都找不到

【问题讨论】:

标签: python python-2.7


【解决方案1】:

您可以使用urllib.urlretrieve()将打开的页面保存到指定路径。

或者你可以用urllib.urlopen()打开url,然后以二进制模式写入读取文件:

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())

【讨论】:

  • 在 Python 3 中,这些函数已移至urllib.request,因此请分别使用urllib.request.retrieveurllib.request.urlopen
  • @AndréTerra 很好,但是问题被标记为python-2.7
  • -1:f.write 不接受 urlopen()。你可以改用shutil.copyfileobj(urllib2.urlopen(url), f)
  • 谢谢!通过传递从.read() 方法返回的字符串对象来修复它
  • 我删除了反对票。虽然copyfileobj 更适合大文件,但.read() 将整个文件加载到内存中
猜你喜欢
  • 2014-11-08
  • 2017-01-01
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 2012-08-24
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多