tags:

views:

118

answers:

4

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.

A: 

Check the mime type and file extension.

Or if this is a one time thing you can use file searching commands in linux.

Kevin
It's the MIME type he's trying to *discover*, and file extensions are useless unless you're in Windows (and there they're hit-and-miss).
Glenn Maynard
So I get voted down, when the one with the most pop votes and accepted answer is basically what I said?
Kevin
I voted that down, too.
Glenn Maynard
Guess I read the initial post wrong, to me it sounds like he wants to know what filetype it is.
Kevin
A: 

If you're on linux you can parse the output of the file command-line tool.

jdizzle
+2  A: 

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

Sinan Ünür
+6  A: 

Use Python's mimetypes library:

import mimetypes
if mimetypes.guess_type('full path to document here')[0] == 'text/plain':
    # file is plaintext
Mike Cialowicz
mimetypes uses the file's filename.ext to determine the file content. It is really easy to spoof that by renaming a file. On a *nix system using the "file" command is safer because it looks inside the file itself to see what the contents look like. "file" can be spoofed too but at least it looks at the contents. Something like python-magic, mentioned by Sinan below, would be safer. For more info do a "man file" and "man magic" on *nix.
Greg
It's interesting that the OP specifically said he can't rely on the file extension, then marked correct an answer that only looks at the file extension...
Glenn Maynard