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仅针对图像文件类型执行相同操作的模块.
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的答案完全相同,但没有这种开销.
Ste*_*ski 10
在unix和linux上有一个file猜测文件类型的命令.甚至还有一个Windows端口.
从手册页:
文件测试每个参数以尝试对其进行分类.按顺序执行三组测试:文件系统测试,幻数测试和语言测试.成功的第一个测试会导致打印文件类型.
您需要file使用subprocess模块运行命令,然后解析结果以找出扩展名.
编辑: 忽略我的回答.请改用Chris Johnson的答案.
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就是这样.你可以通过上面的方式获得命令输出,正如这篇文章所说的那样
在图像的情况下,您可以使用该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 文档
您还可以安装filePython 的官方绑定,一个名为的库file-magic(它不使用ctypes python-magic).
它在PyPI上可用作文件魔法,在Debian上可用作python-magic.对我来说,这个库是最好用的,因为它可以在PyPI和Debian(以及可能的其他发行版)上使用,使得部署软件的过程更容易.我也写过关于如何使用它的博客.
| 归档时间: |
|
| 查看次数: |
103751 次 |
| 最近记录: |