欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

利用Python获取文件类型

程序员文章站 2022-06-27 20:09:39
这里选择使用使用filetype获取文件的类型。 使用filetype之前,先用pip安装filetype。 #!/usr/bin/python3 import filetype import argparse import sys def get_parameter(): parser=argpa ......

这里选择使用使用filetype获取文件的类型。

使用filetype之前,先用pip安装filetype。

#!/usr/bin/python3
import filetype
import argparse
import sys

def get_parameter():
    parser=argparse.argumentparser(description='该脚本用于获取文件的类型')
    parser.add_argument('-f',dest='inputfile',type=str,default='',help='输入待检测文件')
    args=parser.parse_args()
    inputfile=args.inputfile
    return inputfile

def main():
    inputfile=get_parameter()
    if inputfile=='':
        print('请输入待检测文件')
        sys.exit(1)
    ft1=filetype.guess(inputfile)
    if ft1 is none:
        print('无法判断该文件类型')
    print('文件扩展名为:{}'.format(ft1.extension))
    print('文件类型为:{}'.format(ft1.mime))

if __name__=='__main__':
    main()

本脚本运行环境为python3环境。