Get file size from “Content-Length” value from a file in python 3.2

為{幸葍}努か 提交于 2019-12-03 14:59:08

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.

nickanor

for Content-Length:

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

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.

Change final line to:

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

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'])
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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!