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?
The Python Magic library provides the functionality you need.
You can install the library with
pip install python-magic
and use it as follows: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.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-establishedmagic
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.As Steven pointed out,
subprocess
is the way. You can get the command output by the way above as this post saidWith newer subprocess library, you can now use the following code (*nix only solution):
You can also install the official
file
binding for Python, a library calledfile-magic
(it does not use ctypes, likepython-magic
).It's available on PyPI as file-magic and on Debian as python-magic. For me this library is the best to use since it's available on PyPI and on Debian (and probably other distributions), making the process of deploying your software easier. I've blogged about how to use it, also.
In the case of images, you can use the imghdr module.
Python 2 imghdr doc
Python 3 imghdr doc