Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-通过HTTP下载文件并自动检测文件类型_Python_Http - Fatal编程技术网

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

Python-通过HTTP下载文件并自动检测文件类型,python,http,Python,Http,我想通过HTTP下载一个文件,但所有在线示例都涉及获取数据,然后将其放入本地文件。问题是您需要显式设置本地文件的文件类型 我想下载一个文件,但我不知道我下载的文件类型 这就是我目前拥有的: urllib.urlretrieve(fetch_url,output.csv) 但如果我下载,比如说一个XML文件,它将是CSV。有没有办法让python检测从URL发送的文件,如: 假设上面的URL为我提供了一个XML,我希望python能够检测到它。您可以使用它来检测文件类型。它可以通过“pip安装p

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

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

这就是我目前拥有的:

urllib.urlretrieve(fetch_url,output.csv)
但如果我下载,比如说一个XML文件,它将是CSV。有没有办法让python检测从URL发送的文件,如:

假设上面的URL为我提供了一个XML,我希望python能够检测到它。

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

我假设您正在使用Python2.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

你能控制服务器吗?与中一样,服务器是否允许您查询或设置要下载的文件类型?除了尝试将文件解析为多种格式,或者寻找特定的头格式之外,实际上没有通用的“文件类型检测”之类的东西。通常,下载url会包含文件扩展名,这是确定文件类型的一种简单方法。