[英]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.