There is a shell for libmagic for python - pymagic . This is the easiest way to accomplish what you want. Keep in mind that magic is as good as a fingerprint. You may have false positives if something "looks" like a different file format, but in most cases pymagic will give you what you need.
One thing to look out for is a “simple solution” to check if any of the characters are “outside” the printable ASCII range, since you are likely to come across unicode that will look like binary (and , be binary), even if it's just text content.
source
share