如何获取文件的后缀名?



今天面试时被问到了,虽然学过,但是今天被技术问得一脸懵逼啊?废话不多说了,直接上代码吧

测试代码:



运行结果:




加油吧,生猛的程序员们大哭



文件下载链接是动态生成时,可通过以下几种方法获取文件后缀名: ### 从响应头获取 发送HTTP请求获取响应头信息,从响应头的`Content-Disposition`字段中提取后缀名。 ```python import requests import re url = "动态生成的文件下载链接" response = requests.head(url) content_disposition = response.headers.get('Content-Disposition') if content_disposition: match = re.search(r'filename="?([^"]+)"?', content_disposition) if match: filename = match.group(1) file_extension = filename.split('.')[-1] print(file_extension) ``` ### 根据`Content-Type`推断 通过分析响应头中的`Content-Type`字段来推断文件后缀名。不同的`Content-Type`对应不同的文件类型,以下是一些常见的映射关系: | Content-Type | 文件后缀名 | | ---- | ---- | | application/pdf | pdf | | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet | xlsx | | application/msword | doc | | application/vnd.openxmlformats-officedocument.wordprocessingml.document | docx | | application/vnd.ms-excel | xls | ```python import requests url = "动态生成的文件下载链接" response = requests.head(url) content_type = response.headers.get('Content-Type') content_type_mapping = { 'application/pdf': 'pdf', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx', 'application/msword': 'doc', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx', 'application/vnd.ms-excel': 'xls' } if content_type in content_type_mapping: file_extension = content_type_mapping[content_type] print(file_extension) ``` ### 下载部分文件内容分析 如果上述方法都无法获取后缀名,可以下载文件的前几个字节,根据文件的魔数(文件开头的特定字节序列)来判断文件类型。例如,PDF文件的魔数是`%PDF-`。 ```python import requests url = "动态生成的文件下载链接" response = requests.get(url, stream=True) first_bytes = next(response.iter_content(chunk_size=10)) if first_bytes.startswith(b'%PDF-'): file_extension = 'pdf' print(file_extension) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值