当前位置: 代码网 > it编程>前端脚本>Python > Python使用filetype库判断文件类型的完整指南

Python使用filetype库判断文件类型的完整指南

2026年08月25日 Python 我要评论
需求背景判断文件类型在开发中非常常见的需求,怎样才能准确的判断文件类型呢?判断文件的头,每种文件在文件的头中会标识这种文件的类型。对一个文件来说,文件的后缀是可以随意修改的,但是如果改的时间比较长,可

需求背景

判断文件类型在开发中非常常见的需求,怎样才能准确的判断文件类型呢?

判断文件的头,每种文件在文件的头中会标识这种文件的类型。

对一个文件来说,文件的后缀是可以随意修改的,但是如果改的时间比较长,可能就不知道原本的文件格式是啥,不匹配的文件格式,在windows上,大多数情况是无法正常打开的。因此可以根据文件前几个字符的特征码来判断文件真实的格式

用16进制字符串的目的是可以知道文件头是多少字节# 各种文件头的长度不一样,少则2字符,长则8字符

python 根据文件头判断文件类型

python3通过文件头判断文件类型

参考:python3如何通过文件头判断文件类型

import os

# 支持文件类型
# 用16进制字符串的目的是可以知道文件头是多少字节
# 各种文件头的长度不一样,少半2字符,长则8字符

# 支持文件类型
# 用16进制字符串的目的是可以知道文件头是多少字节
# 各种文件头的长度不一样,少半2字符,长则8字符
def typelist():
    print('获取文件格式十六进制码表……');
    return {
        "d0cf11e0a1b11ae10000": 'xls',
        '504b030414': 'docx_docx_xlsx',   #docx, pptx, xlsx
    }

# 字节码转16进制字符串
def bytes2hex(bytes):
    #print('关键码转码……');
    num = len(bytes)
    hexstr = u""
    for i in range(num):
        t = u"%x" % bytes[i]
        if len(t) % 2:
            hexstr += u"0"
        hexstr += t
    return hexstr.upper()


# 获取文件类型
def filetype(filename):
    # docx文件内容为空时,这里会返回
    if os.path.getsize(filename) == 0:
       print("文件内容为空")
       return "xxxx"

    print('读文件二进制码中……');
    binfile = open(filename, 'rb') # 必需二制字读取
    print('读取20字节关键码……');
    bins = binfile.read(20) #提取20个字符
    binfile.close() #关闭文件流
    bins = bytes2hex(bins) #转码
    bins = bins.lower()#小写
    print(bins);
    tl = typelist()  #文件类型
    ftype = 'unknown'
    print('关键码比对中……');
    for hcode in tl.keys():
        lens = len(hcode) # 需要的长度
        if bins[0:lens] == hcode:
            ftype = tl[hcode]
            break
    if ftype == 'unknown':#全码未找到,优化处理,码表取5位验证
        bins = bins[0:5];
        for hcode in tl.keys():
            if len(hcode) > 5 and bins == hcode[0:5]:
                ftype = tl[hcode]
                break
    return ftype


if __name__ == '__main__':
    pathfile = r'd:\tmp\111.xlsx'
    #pathfile = r'd:\tmp\2222.doc'
    #pathfile = r'd:\tmp\3333.docx'
    #pathfile = r'd:\tmp\444.ppt'
    #pathfile = r'd:\tmp\666.pptx'
    #pathfile = r'd:\tmp\sss.txt'

    ftype = filetype(pathfile)
    print(ftype)

常见文件格式的文件头

文件格式 文件头(十六进制)

jpeg (jpg) ffd8ff 
png (png) 89504e47 
gif (gif) 47494638 
tiff (tif) 49492a00 
windows bitmap (bmp) 424d 
cad (dwg) 41433130 
adobe photoshop (psd) 38425053 
rich text format (rtf) 7b5c727466 
xml (xml) 3c3f786d6c 
html (html) 68746d6c3e 
email [thorough only] (eml) 44656c69766572792d646174653a 
outlook express (dbx) cfad12fec5fd746f 
outlook (pst) 2142444e 
ms word/excel (xls.or.doc) d0cf11e0 
ms access (mdb) 5374616e64617264204a

第三方库 filetype

小型无依赖 python 包,用于推断文件类型和 mime 类型,检查文件或缓冲区的神奇数字签名。

filetype模块支持60余种文件类型,下表列出不同文件类型的扩展名

pip install filetype
import os
import filetype

def guessfiletype(pathfile):
    print('guessfiletype %s ...' % pathfile)

    kind = filetype.guess(pathfile)
    if kind is none:
        print('cannot guess file type!')
        return

    print('file name: %s' % os.path.basename(pathfile))
    print('file extension: %s' % kind.extension)
    print('file mime type: %s' % kind.mime)

if __name__ == '__main__':
    #pathfile = r'd:\tmp\111.xlsx'
    #pathfile = r'd:\tmp\2222.doc'
    #pathfile = r'd:\tmp\3333.docx'
    pathfile = r'd:\tmp\444.ppt'
    #pathfile = r'd:\tmp\666.pptx'

    guessfiletype(pathfile)

到此这篇关于python使用filetype库判断文件类型的完整指南的文章就介绍到这了,更多相关python判断文件类型内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com