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])
The Content-Length header indicates the size of the entity body in the message, in bytes. The size includes any content encodings (the Content-Length of a gzip-compressed text file will be the compressed size, not the original size).
Example 1: Using os module Using stat() from the os module, you can get the details of a file. Use the st_size attribute of stat() method to get the file size. The unit of the file size is byte .
The python os module has stat() function where we can pass the file name as argument. This function returns a tuple structure that contains the file information. We can then get its st_size property to get the file size in bytes.
To manually pass the Content-Length header, you need to add the Content-Length: [length] and Content-Type: [mime type] headers to your request, which describe the size and type of data in the body of the POST request.
for Content-Length
:
file_size = int(d.getheader('Content-Length'))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With