python判断文件类型的两个半方法。(Mime、视频、图片、文本)

今天写一个批量命名文件的脚本遇到判定文件所属类型的问题,搜了一下,帖子质量不高,干脆发一个供诸位参考。
为什么说是两个半的方法呢?因为有三种方式,但是两种是同一个模块下的,只差一个语句的效果而已。由于时间原因没有翻译文档,但是相信有点英语水平的都大差不差的能看懂。

1)文件后缀

如果不了解os和os.path模块的这个可以不看。
可以结合os、os.path模块及其字符串的处理,用后缀名判断文件格式。但是前提需要知道后缀名,若是后缀名太多就略显繁琐。

import os
import os.path

address_dir = os.path.dirname(__file__)  # 拿到目录名
address_content_old = os.listdir(address_dir)  # 拿到目录中的每个文件名
address_dir_content_new = []  # 待修改的文件名
for adr_file in address_content_old:  # 根据后缀名判断是否为需要更改的文件
    if os.path.splitext(adr_file)[1] == '.mp4':
        adr_new = os.path.join(address_dir, adr_file)  # 组合成rename需要形式的旧路径
        address_dir_content_new.append(adr_new)

i = 1
# 开始修改,用数字迭代来命名文件
for file_name_old in address_dir_content_new:
    os.rename(file_name_old, os.path.join(address_dir, f'1({i}).mp4'))
    i += 1


2)标准库mimetypes.py模块

该模块是专门用来处理Mime文件类型的,重点是根据文件名来推测文件类型。

'''
def guess_type(url, strict=True)  :基于文件名判断给定文件的文件类型
参数:
	url:文件所在路径(要确保能根据这个路径找到该文件)
	strict:Optional `strict' argument when false adds a bunch of commonly found, but
    non-standard types.
返回值:返回一个字符串元组(type, encoding),type为Mime类型。encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip).
'''

import mimetypes

adr = '抖音\\DYF小视频\\1(3).avi'
print(mimetypes.guess_type(adr))  # ('video/avi', None)

3)第三方库filetype.py模块

这个库也是专门搞文件类型的,但是就判断Mime类型文件来看,没有上面的好用。使用时需要pip安装。


'''第一个
def guess(obj):  # 根据文件内容推测文件类型,若是文件为空,则返回None
    Infers the type of the given input.

    Function is overloaded to accept multiple types in input
    and peform the needed type inference based on it.

    Args:
        obj: path to file, bytes or bytearray.

    Returns:
        The matched type instance. Otherwise None.

    Raises:
        TypeError: if obj is not a supported type.
'''
import filetype

file_type = filetype.guess('C:\\Users\\86138\\Desktop\\小叶同学.jpg')
file_mime = file_type.mime
print(file_type)  # <filetype.types.image.Jpeg object at 0x00000265AD394940>
print(type(file_mime))  # <class 'str'>,虽说这里是字符串,但是字符串的内置方法都用不了,还要手动转换str()。文档里说的是实例,但是type出来是字符串,就这一点令我很不爽。

'''第二种
def guess_mime(obj):  # 同上两者效果仅差一个语句:file_type.mime
    """
    Infers the file type of the given input
    and returns its MIME type.

    Args:
        obj: path to file, bytes or bytearray.

    Returns:
        The matched MIME type as string. Otherwise None.

    Raises:
        TypeError: if obj is not a supported type.
    """
    kind = guess(obj)
    return kind.mime if kind else kind
'''

file_type = filetype.guess_mime('C:\\Users\\86138\\Desktop\\小叶同学.jpg')
print(file_type)  # image/jpeg
print(type(file_type))  # <class 'str'>,同上,也不可用字符串方法

# 总结,这个模块用起来很差劲
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值