How to check if a file contains plain text?

python

Solution

You can use the Python interface to libmagic to identify file formats.

>>> import magic
>>> f = magic.Magic(mime=True)
>>> f.from_file('testdata/test.txt')
'text/plain'

For more examples, see the repo.

Problem

I have a folder full of files and I want to search some string inside them. The issue is that some files may be zip, exe, ogg, etc. Can I check somehow what kind of file is it so I only open and search through txt, PHP, etc. files. I can't rely on the file extension.

Original source