Get file size from “Content-Length” value from a f

2020-06-16 09:27发布

I want to get the Content-Length value from the meta variable. I need to get the size of the file that I want to download. But the last line returns an error, HTTPMessage object has no attribute 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条回答
老娘就宠你
2楼-- · 2020-06-16 09:35

response.headers['Content-Length'] works on both Python 2 and 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'])
查看更多
你好瞎i
3楼-- · 2020-06-16 09:39

You should consider using Requests:

import requests

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

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

For Python 3, use:

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

instead.

查看更多
▲ chillily
4楼-- · 2020-06-16 09:47

Change final line to:

file_size = int(meta.get_all("Content-Length")[0])
查看更多
5楼-- · 2020-06-16 09:48

It looks like you are using Python 3, and have read some code / documentation for Python 2.x. It is poorly documented, but there is no getheaders method in Python 3, but only a get_all method.

See this bug report.

查看更多
劫难
6楼-- · 2020-06-16 09:48

for Content-Length:

file_size = int(d.getheader('Content-Length'))
查看更多
该账号已被封号
7楼-- · 2020-06-16 09:49
import urllib.request

link = "<url here>"

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

Works with python 3.x

查看更多
登录 后发表回答