emnoor emnoor - 2 years ago 451
Python Question

How to check type of files without extensions in python?

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

returns file type like
. I want to do this:

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

How do I do this?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download