You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Python代码获取PDF、Word、PNG等文件的type-size属性?

Python读取多类型文件并输出类型-大小属性

核心思路

  • 文件大小:通过内置os模块的os.path.getsize()获取,单位为字节。
  • 文件真实类型:避免仅依赖扩展名判断,使用python-magic库检测文件的MIME类型,结果更准确。

所需依赖

安装必要的第三方库:

# Linux/macOS环境
pip install python-magic

# Windows系统建议安装适配版本
pip install python-magic-bin

实现代码

import os
import magic

def get_file_type_and_size(file_path):
    # 检查文件是否存在
    if not os.path.isfile(file_path):
        return "文件不存在", 0
    
    # 获取文件大小(字节)
    file_size = os.path.getsize(file_path)
    
    # 获取文件真实类型
    try:
        mime_type = magic.from_file(file_path, mime=True)
        # 简化类型显示,提取主类型(如image、application)
        simple_type = mime_type.split('/')[0] if '/' in mime_type else mime_type
    except Exception as e:
        simple_type = f"类型检测失败: {str(e)}"
    
    return simple_type, file_size

# 示例1:处理单个文件
file_path = "test.pdf"  # 替换为你的目标文件路径
file_type, file_size = get_file_type_and_size(file_path)
print(f"{file_type}-{file_size}字节")

# 示例2:遍历目录下所有文件
target_dir = "./target_files"  # 替换为你的目标目录
for filename in os.listdir(target_dir):
    full_path = os.path.join(target_dir, filename)
    if os.path.isfile(full_path):
        f_type, f_size = get_file_type_and_size(full_path)
        print(f"{filename}: {f_type}-{f_size}字节")

补充说明

  1. 大小单位转换:如果需要将字节转换为KB/MB,可自行计算(如file_size / 1024得到KB值)。
  2. 详细类型显示:若需要完整的MIME类型(如application/pdf、image/png),直接返回mime_type即可,无需拆分。
  3. 异常扩展:代码仅做了基础异常处理,可根据需求添加权限校验、大文件处理等逻辑。

内容的提问来源于stack exchange,提问作者MANEL25

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 12:52:43