Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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])
like image 240
scandalous Avatar asked Oct 21 '12 08:10

scandalous


People also ask

Is content-length the same as file size?

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).

Which calculates the size of a file in Python?

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 .

How does Python compare files in size?

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.

How do I set the content-length in an HTTP header?

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.


2 Answers

for Content-Length:

file_size = int(d.getheader('Content-Length'))
like image 146
nickanor Avatar answered Oct 21 '22 10:10

nickanor


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.

like image 35
Krumelur Avatar answered Oct 21 '22 09:10

Krumelur