如何在python中检查没有扩展名的文件类型?

时间:2012-06-07 18:06:41

标签: python filesystems identification

我有一个文件夹,这些文件没有扩展名。我该如何检查文件类型?我想检查文件类型并相应地更改文件名。假设函数filetype(x)返回类似png的文件类型。我想这样做:

files = os.listdir(".")
for f in files:
    os.rename(f, f+filetype(f))

我该怎么做?

9 个答案:

答案 0 :(得分:69)

有些Python库可以根据文件内容(通常是标题/幻数)来识别文件,并且不依赖于文件名或扩展名。

如果您要处理许多不同的文件类型,则可以使用python-magic。这只是一个完善的magic库的Python绑定。这有着良好的声誉和(小代言)在我使用它的有限用途,它是坚实的。

还有用于更专业文件类型的库。例如,Python标准库具有imghdr模块,它只对图像文件类型执行相同的操作。

答案 1 :(得分:52)

Python Magic库提供您需要的功能。

您可以使用pip install python-magic安装库,并按如下方式使用它:

>>> import magic

>>> magic.from_file('iceland.jpg')
'JPEG image data, JFIF standard 1.01'

>>> magic.from_file('iceland.jpg', mime=True)
'image/jpeg'

>>> magic.from_file('greenland.png')
'PNG image data, 600 x 1000, 8-bit colormap, non-interlaced'

>>> magic.from_file('greenland.png', mime=True)
'image/png'

在这种情况下,Python代码调用引擎盖下的libmagic,它与* NIX file命令使用的库相同。因此,这与基于子进程/ shell的答案完全相同,但没有这种开销。

答案 2 :(得分:10)

在unix和linux上有file命令来猜测文件类型。甚至有windows port

来自man page

  

文件测试每个参数以尝试对其进行分类。有三种   按以下顺序执行的测试集:文件系统测试,幻数   测试和语言测试。成功的第一个测试导致了   要打印的文件类型。

您需要使用file模块运行subprocess命令,然后解析结果以找出扩展名。

编辑:忽略我的回答。请改用Chris Johnson的answer

答案 3 :(得分:6)

import subprocess
p = sub.Popen('file yourfile.txt',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
print output

史蒂文指出,subprocess就是这样。您可以通过上面的方式获得命令输出,如post所述

答案 4 :(得分:6)

您还可以为Python安装官方file绑定,这是一个名为file-magic的库(它不使用ctypes,如python-magic)。

它在PyPI上可用file-magic,在Debian上可用python-magic。对我来说,这个库是最好用的,因为它可以在PyPI和Debian(以及可能的其他发行版)上使用,使得部署软件的过程更容易。 我也是blogged about how to use it

答案 5 :(得分:3)

使用较新的子进程库,您现在可以使用以下代码(仅限* nix解决方案):

import subprocess
import shlex

filename = 'your_file'
cmd = shlex.split('file --mime-type {0}'.format(filename))
result = subprocess.check_output(cmd)
mime_type = result.split()[-1]
print mime_type

答案 6 :(得分:3)

对于图像,您可以使用imghdr模块。

>>> import imghdr
>>> imghdr.what('8e5d7e9d873e2a9db0e31f9dfc11cf47')  # You can pass a file name or a file object as first param. See doc for optional 2nd param.
'png'

Python 2 imghdr doc
Python 3 imghdr doc

答案 7 :(得分:1)

仅适用于Linux,但是使用“ sh” python模块,您可以简单地调用任何shell命令

https://pypi.org/project/sh/

pip install sh

  

导入sh

     

sh.file( “/根/文件”)

输出: /根/文件:ASCII文本

答案 8 :(得分:0)

您也可以使用此代码(标头文件3字节的纯python):

full_path = os.path.join(MEDIA_ROOT, pathfile)

try:
    image_data = open(full_path, "rb").read()
except IOError:
    return "Incorrect Request :( !!!"

header_byte = image_data[0:3].encode("hex").lower()

if header_byte == '474946':
    return "image/gif"
elif header_byte == '89504e':
    return "image/png"
elif header_byte == 'ffd8ff':
    return "image/jpeg"
else:
    return "binary file"
  

不安装任何软件包[和更新版本]