当前位置: 首页 > 工具软件 > python-magic > 使用案例 >

python-magic获取文件格式

充栋
2023-12-01

安装Python-magic

pip install python-magic python-magic-bin libmagic

import magic
import os

def list_all_files(rootdir):
    import os
    _files = []
    list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
    for i in range(0,len(list)):
           path = os.path.join(rootdir,list[i])
           if os.path.isdir(path):
              _files.extend(list_all_files(path))
           if os.path.isfile(path):
              _files.append(path)
    return _files

def main():
    m = magic.Magic()
    for file in list_all_files("C:\\Users\\Downloads"):
        file_type = m.from_buffer(open(file,"rb").read(1024))
        print(file_type)


if __name__ == '__main__':
    main()

1.到https://github.com/ahupp/python-magic 下载,编译,安装python-magic

2. 到 http://sourceforge.net/projects/gnuwin32/files/file/5.03/  下载 file-5.03-setup.exe

3. 安装到 C:\GnuWin

 类似资料: