0

I have a file I'd like Python to find out and print its file size. Unfortunately, the headers do not have the key content-length. Is there a workaround to finding the file size without content-length? Thanks.

import requests

link = "https://web.archive.org/cdx/search/cdx?url=twitter.com/realdonaldtrump/status&matchType=prefix&filter=statuscode:200"

response = requests.head(link)
print(response.headers['content-length'])

Error:

    return self._store[key.lower()][1]
KeyError: 'content-length'
  • I'm not sure, but something in this link may help you: https://stackoverflow.com/questions/3854842/content-length-header-with-head-requests – FLAK-ZOSO Feb 05 '22 at 15:26
  • Did you try saving the file and then checking the size of the local file, the same way you would with any other file? If the point is to warn the user about file size before downloading, I'm afraid you're out of luck; it's up to the server to tell you that, and some servers don't. Or it might depend on what the file is - if the server has to create it on the fly, it might not want to figure out the length ahead of time. That's why graphical programs have an option to abort downloads. – Karl Knechtel Feb 05 '22 at 15:36
  • You are correct. I want to give the user an idea about how long they'll have to wait. I'm afraid that in this case, it isn't possible. I can save the file and find its size locally, but that's impossible to do if parts of the URL are variable. I'll just let the user know it might be a long wait. Thank you Karl, appreciate your time :) – facialrecognition Feb 05 '22 at 15:41

0 Answers0