从python 3.2中的文件中获取“Content-Length”值的文件大小

时间:2012-10-21 08:42:21

标签: python http python-3.x urllib

我想从元变量中获取Content-Length值。我需要获取我要下载的文件的大小。但是最后一行返回错误,HTTPMessage对象没有属性getheaders

import urllib.request
import http.client

#----HTTP HANDLING PART----
 url = "http://client.akamai.com/install/test-objects/10MB.bin"

file_name = url.split('/')[-1]
d = urllib.request.urlopen(url)
f = open(file_name, 'wb')

#----GET FILE SIZE----
meta = d.info()

print ("Download Details", meta)
file_size = int(meta.getheaders("Content-Length")[0])

6 个答案:

答案 0 :(得分:11)

看起来您正在使用Python 3,并且已经阅读了Python 2.x的一些代码/文档。记录很少,但Python 3中没有getheaders方法,只有get_all方法。

请参阅this bug report

答案 1 :(得分:6)

代表Content-Length

file_size = int(d.getheader('Content-Length'))

答案 2 :(得分:4)

您应该考虑使用Requests

import requests

url = "http://client.akamai.com/install/test-objects/10MB.bin"
resp = requests.get(url)

print resp.headers['content-length']
# '10485760'

对于Python 3,请使用:

print(resp.headers['content-length'])

代替。

答案 3 :(得分:1)

将最后一行更改为:

file_size = int(meta.get_all("Content-Length")[0])

答案 4 :(得分:1)

response.headers['Content-Length']适用于Python 2和3:

#!/usr/bin/env python
from contextlib import closing

try:
    from urllib2 import urlopen
except ImportError: # Python 3
    from urllib.request import urlopen


with closing(urlopen('http://stackoverflow.com/q/12996274')) as response:
    print("File size: " + response.headers['Content-Length'])

答案 5 :(得分:0)

import urllib.request

link = "<url here>"

f = urllib.request.urlopen(link)
meta = f.info()
print (meta.get("Content-length"))
f.close()

使用python 3.x