gpt4 book ai didi

Python - 通过 HTTP 下载文件并自动检测文件类型

转载 作者:可可西里 更新时间:2023-11-01 17:00:36 24 4
gpt4 key购买 nike

我想通过 HTTP 下载一个文件,但所有在线示例都涉及获取数据,然后将其放入本地文件。这样做的问题是您需要显式设置本地文件的文件类型。

我想下载一个文件,但我不知道我正在下载的文件类型。

这是我目前拥有的:

urllib.urlretrieve(fetch_url,output.csv)

但是如果我下载一个 XML 文件,它将是 CSV。无论如何让 python 检测我从 URL 发送的文件,如:http://asassaassa.com/assaas?abc=123

假设上面的 URL 给了我一个 XML,我希望 python 检测它。

最佳答案

您可以使用 python-magic检测文件类型。它可以通过“pip install python-magic”安装。

我假设您使用的是 python 2.7,因为您正在调用 urlretreieve。该示例适用于 2.7,但很容易适应。

这是一个工作示例:

import mimetypes # Detects mimetype
import magic # Uses magic numbers to detect file type, and does so much better than the built in mimetypes
import urllib # Your library
import os # for renaming your file
mime = magic.Magic(mime=True)
output = "output" # Your file name without extension
urllib.urlretrieve("https://docs.python.org/3.0/library/mimetypes.html", output) # This is just an example url
mimes = mime.from_file(output) # Get mime type
ext = mimetypes.guess_all_extensions(mimes)[0] # Guess extension
os.rename(output, output+ext) # Rename file

关于Python - 通过 HTTP 下载文件并自动检测文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38710238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com