![](/img/trans.png)
[英]How to determine the Content-Length of a gzipped file in Python?
[英]Get file size from “Content-Length” value from a file in python 3.2
我想从元变量中获取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])
看起来您正在使用Python 3,并且已经阅读了Python 2.x的一些代码/文档。 它的文档很少,但Python 3中没有getheaders
方法,只有get_all
方法。
请参阅此错误报告 。
for Content-Length
:
file_size = int(d.getheader('Content-Length'))
您应该考虑使用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'])
代替。
将最后一行更改为:
file_size = int(meta.get_all("Content-Length")[0])
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'])
import urllib.request
link = "<url here>"
f = urllib.request.urlopen(link)
meta = f.info()
print (meta.get("Content-length"))
f.close()
适用于python 3.x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.