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

emn*_*oor 65 python filesystems identification

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

files = os.listdir(".")
for f in files:
    os.rename(f, f+filetype(f))
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

Chr*_*son 71

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

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

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

  • 包 [`python-magic-win64`](https://github.com/axnsan12/python-magic-win64) 在 Windows 中为我工作 (3认同)
  • [imghdr](https://docs.python.org/3/library/imghdr.html) 与 [filetype](https://pypi.org/project/filetype/) 的组合在 Windows 中为我工作 (2认同)
  • 自版本 3.11 起,[imghdr](https://docs.python.org/3/library/imghdr.html#module-imghdr) 模块已弃用 (2认同)
  • 另请注意,**filetype** 和 **python-magic** 可能会产生完全不同的结果,例如,如果您有一个“*.docx”文件,则 filetype 将“application/zip”报告为 MIME 类型(因为本质上docx 文件由包含 XML 文档的 zip 容器组成),而 python-magic 则表示“application/vnd.openxmlformats-officedocument.wordprocessingml.document”,这更精确(即它查看 ZIP 容器内部)。 (2认同)

Ric*_*ard 54

Python的魔术库提供您需要的功能.

您可以安装库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'
Run Code Online (Sandbox Code Playgroud)

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

  • 请注意,名为python-magic的debian/ubuntu包与同名的pip包不同.两者都是`import magic`但内容不兼容.有关更多信息,请参见http://stackoverflow.com/a/16203777/3189. (4认同)
  • 非常棒的答案。如果您看到“无法找到 libmagic”。检查您的安装,然后运行“brew install libmagic”并重试 (2认同)

Ste*_*ski 10

在unix和linux上有一个file猜测文件类型的命令.甚至还有一个Windows端口.

手册页:

文件测试每个参数以尝试对其进行分类.按顺序执行三组测试:文件系统测试,幻数测试和语言测试.成功的第一个测试会导致打印文件类型.

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

编辑: 忽略我的回答.请改用Chris Johnson的答案.

  • +1使用`file`命令的一个好处是它在(大多数?)Linux发行版上是原生的,而`python-magic`不是,必须先下载并安装才能使用它.如果使用该模块的脚本应该是可移植的,这有点问题. (2认同)

xva*_*tar 7

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

正如史蒂文指出的那样,subprocess就是这样.你可以通过上面的方式获得命令输出,正如这篇文章所说的那样


Lew*_*ond 7

在图像的情况下,您可以使用该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'
Run Code Online (Sandbox Code Playgroud)

Python 2 imghdr 文档
Python 3 imghdr 文档


Álv*_*ten 6

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

它在PyPI上可用作文件魔法,在Debian上可用作python-magic.对我来说,这个库是最好用的,因为它可以在PyPI和Debian(以及可能的其他发行版)上使用,使得部署软件的过程更容易.我也写过关于如何使用它的博客.


归档时间:

查看次数:

103751 次

最近记录:

6 年,2 月 前