pythonfilesystemsidentification

How to check type of files without extensions?


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?


Solution

  • 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.

    The native imghdr library can be useful, but is deprecated since Python 3.11 and will be removed in Python 3.13.

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