如何检查在Python中没有扩展名的文件类型? [英] How to check type of files without extensions in python?

查看:194
本文介绍了如何检查在Python中没有扩展名的文件类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我该怎么做有些Python库可以根据它们的内容(通常是头/幻数)来识别文件,而且不用担心, t依赖于文件名或扩展名。



如果您正在处理多种不同的文件类型,可以使用 蟒幻 。这只是一个已经建立的 magic 库的Python绑定。这在我用它做的有限使用方面有很好的声誉和(小的认可),它已经是稳固的。

还有更多专门文件类型的库。例如,Python标准库有 imghdr 模块它只为图像文件类型做同样的事情。


I have a folder full of files and these doesn't have an extension. How can I check file types? I want to check the file type and change the filename accordingly. Let's assume a function filetype(x) returns file type like png. I want to do this:

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

How do I do this?

解决方案

There are Python libraries that can recognize files based on their content (usually a header / magic number) and that don't rely on the file name or extension.

If you're addressing many different file types, you can use python-magic. That's just a Python binding for the well-established magic library. This has a good reputation and (small endorsement) in the limited use I've made of it, it has been solid.

There are also libraries for more specialized file types. For example, the Python standard library has the imghdr module that does the same thing just for image file types.

这篇关于如何检查在Python中没有扩展名的文件类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆