首页 / 操作系统 / Linux / Python获取远程文件大小函数示例
分享一个Python获取远程文件大小的函数代码,简单实用,是学习Python编程的基础实例。代码:def getRemoteFileSize(url, proxy=None):
""" 通过content-length头获取远程文件大小
url - 目标文件URL
proxy - 代理 """
opener = urllib2.build_opener()
if proxy:
if url.lower().startswith("https://"):
opener.add_handler(urllib2.ProxyHandler({"https" : proxy}))
else: www.linuxidc.com
opener.add_handler(urllib2.ProxyHandler({"http" : proxy}))
try:
request = urllib2.Request(url)
request.get_method = lambda: "HEAD"
response = opener.open(request)
response.read()
except Exception, e: # 远程文件不存在
return 0
else:
fileSize = dict(response.headers).get("content-length", 0)
return int(fileSize)《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htmPython脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htmPython 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htmPython 的详细介绍:请点这里
Python 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-01/111136.htm