Get the size of a file from URL in Python

 

方法一:

使用python标准库中urllib:

import urllib.request
file = urllib.request.urlopen("https://speed.hetzner.de/100MB.bin")
print(file.length)

 

 

方法二:

安装强大的三方库requests

pip install requests

 

The head() method requests the URL to give access to the header details of the file. This is very useful when you only need the status and basic details of the file and not it’s contents.

import requests
url = "https://speed.hetzner.de/100MB.bin"
info = requests.head(url)
print(info.headers)

 

The ‘Content-Length’ gives the size of the file in bytes.

 

 

参考:

https://stackoverflow.com/questions/14270698/get-file-size-using-python-requests-while-only-getting-the-header

https://www.codespeedy.com/get-the-size-of-a-file-from-url-in-python/

 

posted @ 2021-05-16 23:06  profesor  阅读(61)  评论(0编辑  收藏  举报