Python下判断文件是否为二进制文件方法

工作过程中需要判断文件类型可以用一下两个方法,具体如下:
方法一
利用magic模块
先安装magic模块pip install python-magic

import re

import magic
def get_file_type(file_pwd):
    """
    判断文件是否是二进制可执行文件
    :param file_pwd:
    :return:
    """
    flag = False
    mime_kw = 'x-executable|x-sharedlib|octet-stream|x-object'  ###可执行文件、链接库、动态流、对象
    try:
        magic_mime = magic.from_file(file_pwd, mime=True)
        magic_hit = re.search(mime_kw, magic_mime, re.I)
        if magic_hit:
            flag = True
    except Exception as e:
        print(e)
    return flag

返回结果为TRUE时文件为二进制文件

方法二

# 判断文件是否是elf文件
def is_ELFfile(filepath):
    if not os.path.exists(filepath):
        logger.info('file path {} doesnot exits'.format(filepath))
        return False
    # 文件可能被损坏,捕捉异常
    try:
        FileStates = os.stat(filepath)
        FileMode = FileStates[stat.ST_MODE]
        if not stat.S_ISREG(FileMode) or stat.S_ISLNK(FileMode):  # 如果文件既不是普通文件也不是链接文件
            return False
        with open(filepath, 'rb') as f:
            header = (bytearray(f.read(4))[1:4]).decode(encoding="utf-8")
            # logger.info("header is {}".format(header))
            if header in ["ELF"]:
                # print header
                return True
    except UnicodeDecodeError as e:
        # logger.info("is_ELFfile UnicodeDecodeError {}".format(filepath))
        # logger.info(str(e))
        pass

    return False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值