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?
You can check the file extension from the Type column in Windows file explorer. Alternatively, you could right-click on the file and select Properties. You'll see the Type of file in the General tab of file properties. If it says File, you know that the file has no extension.
Windows file names have two parts; the file's name, then a period followed by the extension (suffix). The extension is a three- or four-letter abbreviation that signifies the file type. For example, in letter. docx the filename is letter and the extension is docx.
What about files with no extension? Unlike the Macintosh which embeds creator information into files so they can have just about any name, a PC still mostly uses file extensions to associate programs with files. But, what do you do with a file that has no extension? The simple answer is: punt.
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
.
The Python Magic library provides the functionality you need.
You can install the library with pip install python-magic
and use it as follows:
>>> 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'
The Python code in this case is calling to libmagic beneath the hood, which is the same library used by the *NIX file
command. Thus, this does the same thing as the subprocess/shell-based answers, but without that overhead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With