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.
views:
118answers:
4
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
2010-03-18 17:57:58
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
2010-03-18 22:27:33
So I get voted down, when the one with the most pop votes and accepted answer is basically what I said?
Kevin
2010-03-18 22:32:23
I voted that down, too.
Glenn Maynard
2010-03-19 01:06:16
Guess I read the initial post wrong, to me it sounds like he wants to know what filetype it is.
Kevin
2010-03-19 01:17:16
A:
If you're on linux you can parse the output of the file command-line tool.
jdizzle
2010-03-18 17:58:17
+2
A:
You can use the Python interface to libmagic to identify file formats.
Sinan Ünür
2010-03-18 17:58:47
+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
2010-03-18 18:01:02
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
2010-03-18 19:29:25
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
2010-03-18 22:26:12