0

I'm in the process of writing a python script, and I want to find out information about a file, such as for example a mime-type (or any useful depiction of what a file contains).

I've heard about python-magic, but I'm really looking for the solution that will allow me to find this information, without requiring the installation of additional packages.

Am I stuck to maintaining a list of file extensions, or does python have something in the standard library? I was not able to find it in the docs.

Evert
  • 75,014
  • 17
  • 95
  • 156
  • Duplicate: http://stackoverflow.com/questions/43580/how-to-find-the-mime-type-of-a-file-in-python – S.Lott Apr 22 '09 at 10:44

2 Answers2

5

I am not sure if you want to infer something from file content but if you want to know mime type from file extension mimetypes module will be sufficient

>>> import mimetypes
>>> mimetypes.init()
>>> mimetypes.knownfiles
['/etc/mime.types', '/etc/httpd/mime.types', ... ]
>>> mimetypes.suffix_map['.tgz']
'.tar.gz'
>>> mimetypes.encodings_map['.gz']
'gzip'
>>> mimetypes.types_map['.tgz']
'application/x-tar-gz'

http://docs.python.org/library/mimetypes.html

Anurag Uniyal
  • 77,208
  • 39
  • 164
  • 212
1

The standard library has support for mapping filenames to mimetypes.

Your question also sounds like you are interested in other information besides mimetype. The stat module will also give you information about size, owner, time of last modification, etc. but otherwise the most common filesystems (Windows NTFS/FAT, Linux Ext 2/3, Mac OS X) do not store any metadata or "other information" about files. That's why we need to use extensions to find the mimetype for example.

Van Gale
  • 41,789
  • 9
  • 67
  • 78