Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python 判断文件类型

作者:二分醒amor   发布日期:2025-05-16   浏览:55

import mimetypes

def get_file_type(file_path):
    # 使用mimetypes库来猜测文件类型
    content_type, _ = mimetypes.guess_type(file_path)
    return content_type

# 示例用法
file_path = 'example.txt'
file_type = get_file_type(file_path)
print(f"文件 {file_path} 的类型是: {file_type}")

解释说明:

  1. 导入 mimetypes 模块:这个模块用于根据文件扩展名猜测文件的 MIME 类型。
  2. 定义 get_file_type 函数:该函数接收一个文件路径作为参数,并使用 mimetypes.guess_type 方法来猜测文件的 MIME 类型。
  3. 返回文件类型mimetypes.guess_type 返回一个元组,其中第一个元素是 MIME 类型(如 text/plain),第二个元素是编码方式(通常为 None)。我们只关心 MIME 类型,所以使用下划线 _ 忽略编码信息。
  4. 示例用法:演示如何调用 get_file_type 函数并打印文件类型。

如果你需要更复杂的文件类型判断(例如基于文件内容而不是扩展名),可以考虑使用其他库如 filetypemagic

上一篇:python取字符串前几位

下一篇:for i in range在python中的用法

大家都在看

python时间格式

python ord和chr

python中的yield

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

python 输出时间

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站