Content-Type Guesser

Walter Dörwald walter at livinglogic.de
Wed Jul 24 08:37:15 EDT 2002


Thomas Guettler wrote:
> Hi!
> 
> Has someone a function for guessing the content type
> given a filename?
> 
> foo.xml --> text/xml
> foo.html --> text/html
> ....
> 
> It should work for the most common file-extensions

Python 2.2.1 (#1, Apr 10 2002, 19:08:12)
[GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import mimetypes
 >>> help(mimetypes.guess_type)
Help on function guess_type in module mimetypes:

guess_type(url, strict=1)
     Guess the type of a file based on its URL.

     Return value is a tuple (type, encoding) where type is None if the
     type can't be guessed (no or unknown suffix) or a string of the
     form type/subtype, usable for a MIME Content-type header; and
     encoding is None for no encoding or the name of the program used
     to encode (e.g. compress or gzip).  The mappings are table
     driven.  Encoding suffixes are case sensitive; type suffixes are
     first tried case sensitive, then case insensitive.

     The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped
     to ".tar.gz".  (This is table-driven too, using the dictionary
     suffix_map).

     Optional `strict' argument when false adds a bunch of commonly 
found, but
     non-standard types.

Hope that helps,
    Walter Dörwald




More information about the Python-list mailing list