How to check type of files without extensions in python?

emnoor picture emnoor · Jun 7, 2012 · Viewed 138.8k times · Source

I have a folder full of files and they don'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 a 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?

Answer

Chris Johnson picture Chris Johnson · Jun 7, 2012

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.

If you need dependency-free (pure Python) file type checking, see filetype.