M
M
Mixa2021-11-30 19:00:48
Python
Mixa, 2021-11-30 19:00:48

How to download a file in Python without knowing its name and extension?

How to download a file in python from a link that does not contain information about the name and file format?

For example, here is a link:
https://lh4.ggpht.com/HSXdsQpFEOTgh0QywV4NzNJIPADn...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2021-11-30
@fox_12

61a657f355acd672328824.jpeg

V
Vasily Bannikov, 2021-11-30
@vabka

Actually, the content-disposition header specifies the name and extension of the file: inline;filename="unnamed.jpg"
But in general, yes - just when saving the general, the name is random.

import requests
response = requests.get("https://lh4.ggpht.com/HSXdsQpFEOTgh0QywV4NzNJIPADnWnkCVOsMmQkIgG9K08pQcwpNiWlu3Ls73mzYMTM")
filename  = response.headers["Content-Disposition"].split(";")[1].split("=")[1].strip('"') #вместо этого можно сгенерить случайное имя
file = open(filename, "wb")
file.write(response.content)
file.close()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question