mimetypes — Map filenames to MIME types (2024)

Código-fonte: Lib/mimetypes.py

O módulo mimetypes converte entre um nome de arquivo ou URL e o tipo MIME associado à extensão do arquivo. As conversões são fornecidas do nome do arquivo para o tipo MIME e da extensão do tipo MIME para o nome do arquivo; codificações não são suportadas para a última conversão.

O módulo fornece uma classe e várias funções convenientes. As funções são a interface normal para este módulo, mas algumas aplicações também podem estar interessadas na classe.

As funções descritas abaixo fornecem a interface principal para este módulo. Se o módulo não foi inicializado, eles chamarão init() se confiarem nas informações init() configuradas.

mimetypes.guess_type(url, strict=True)

Adivinha o tipo de arquivo com base em seu nome de arquivo, caminho ou URL, fornecido por url. A URL pode ser uma string ou um objeto caminho ou similar.

O valor de retorno é uma tupla (type, encoding) onde o tipo é None se o tipo não puder ser ser adivinhado (sufixo ausente ou desconhecido) ou uma string no formato 'type/subtype', utilizável para um cabeçalho MIME content-type.

encoding é None para nenhuma codificação ou o nome do programa usado para codificar (por exemplo compress ou gzip). A codificação é adequada para uso como cabeçalho Content-Encoding , não como cabeçalho Content-Transfer-Encoding. Os mapeamentos são orientados por tabela. Os sufixos de codificação diferenciam maiúsculas de minúsculas; os sufixos de tipo são testados primeiro com maiúsculas e minúsculas e depois sem maiúsculas.

O argumento opcional strict é um sinalizador que especifica se a lista de tipos MIME conhecidos é limitada apenas aos tipos oficiais registrados na IANA. Quando strict é True (o padrão), apenas os tipos IANA são suportados; quando strict é False, alguns tipos MIME adicionais não padronizados, mas geralmente usados, também são reconhecidos.

Alterado na versão 3.8: Added support for url being a path-like object.

Obsoleto desde a versão 3.13: Passing a file path instead of URL is soft deprecated.Use guess_file_type() for this.

mimetypes.guess_file_type(path, *, strict=True)

Guess the type of a file based on its path, given by path.Similar to the guess_type() function, but accepts a path instead of URL.Path can be a string, a bytes object or a path-like object.

Adicionado na versão 3.13.

mimetypes.guess_all_extensions(type, strict=True)

Guess the extensions for a file based on its MIME type, given by type. Thereturn value is a list of strings giving all possible filename extensions,including the leading dot ('.'). The extensions are not guaranteed to havebeen associated with any particular data stream, but would be mapped to the MIMEtype type by guess_type() and guess_file_type().

O argumento opcional strict tem o mesmo significado que com a função guess_type().

mimetypes.guess_extension(type, strict=True)

Guess the extension for a file based on its MIME type, given by type. Thereturn value is a string giving a filename extension, including the leading dot('.'). The extension is not guaranteed to have been associated with anyparticular data stream, but would be mapped to the MIME type type byguess_type() and guess_file_type().If no extension can be guessed for type, None is returned.

O argumento opcional strict tem o mesmo significado que com a função guess_type().

Some additional functions and data items are available for controlling thebehavior of the module.

mimetypes.init(files=None)

Initialize the internal data structures. If given, files must be a sequenceof file names which should be used to augment the default type map. If omitted,the file names to use are taken from knownfiles; on Windows, thecurrent registry settings are loaded. Each file named in files orknownfiles takes precedence over those named before it. Callinginit() repeatedly is allowed.

Specifying an empty list for files will prevent the system defaults frombeing applied: only the well-known values will be present from a built-in list.

If files is None the internal data structure is completely rebuilt to itsinitial default value. This is a stable operation and will produce the same resultswhen called multiple times.

Alterado na versão 3.2: Previously, Windows registry settings were ignored.

mimetypes.read_mime_types(filename)

Load the type map given in the file filename, if it exists. The type map isreturned as a dictionary mapping filename extensions, including the leading dot('.'), to strings of the form 'type/subtype'. If the file filenamedoes not exist or cannot be read, None is returned.

mimetypes.add_type(type, ext, strict=True)

Add a mapping from the MIME type type to the extension ext. When theextension is already known, the new type will replace the old one. When the typeis already known the extension will be added to the list of known extensions.

When strict is True (the default), the mapping will be added to theofficial MIME types, otherwise to the non-standard ones.

mimetypes.inited

Flag indicating whether or not the global data structures have been initialized.This is set to True by init().

mimetypes.knownfiles

List of type map file names commonly installed. These files are typically namedmime.types and are installed in different locations by differentpackages.

mimetypes.suffix_map

Dictionary mapping suffixes to suffixes. This is used to allow recognition ofencoded files for which the encoding and the type are indicated by the sameextension. For example, the .tgz extension is mapped to .tar.gzto allow the encoding and type to be recognized separately.

mimetypes.encodings_map

Dictionary mapping filename extensions to encoding types.

mimetypes.types_map

Dictionary mapping filename extensions to MIME types.

mimetypes.common_types

Dictionary mapping filename extensions to non-standard, but commonly found MIMEtypes.

An example usage of the module:

>>> 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'

Objetos MimeTypes

The MimeTypes class may be useful for applications which may want morethan one MIME-type database; it provides an interface similar to the one of themimetypes module.

class mimetypes.MimeTypes(filenames=(), strict=True)

This class represents a MIME-types database. By default, it provides access tothe same database as the rest of this module. The initial database is a copy ofthat provided by the module, and may be extended by loading additionalmime.types-style files into the database using the read() orreadfp() methods. The mapping dictionaries may also be cleared beforeloading additional data if the default data is not desired.

The optional filenames parameter can be used to cause additional files to beloaded “on top” of the default database.

suffix_map

Dictionary mapping suffixes to suffixes. This is used to allow recognition ofencoded files for which the encoding and the type are indicated by the sameextension. For example, the .tgz extension is mapped to .tar.gzto allow the encoding and type to be recognized separately. This is initially acopy of the global suffix_map defined in the module.

encodings_map

Dictionary mapping filename extensions to encoding types. This is initially acopy of the global encodings_map defined in the module.

types_map

Tuple containing two dictionaries, mapping filename extensions to MIME types:the first dictionary is for the non-standards types and the second one is forthe standard types. They are initialized by common_types andtypes_map.

types_map_inv

Tuple containing two dictionaries, mapping MIME types to a list of filenameextensions: the first dictionary is for the non-standards types and thesecond one is for the standard types. They are initialized bycommon_types and types_map.

guess_extension(type, strict=True)

Similar to the guess_extension() function, using the tables stored as partof the object.

guess_type(url, strict=True)

Similar to the guess_type() function, using the tables stored as part ofthe object.

guess_file_type(path, *, strict=True)

Similar to the guess_file_type() function, using the tables storedas part of the object.

Adicionado na versão 3.13.

guess_all_extensions(type, strict=True)

Similar to the guess_all_extensions() function, using the tables storedas part of the object.

read(filename, strict=True)

Load MIME information from a file named filename. This uses readfp() toparse the file.

If strict is True, information will be added to list of standard types,else to the list of non-standard types.

readfp(fp, strict=True)

Carrega informações do tipo MIME de um arquivo aberto fp. O arquivo precisa estar no formato padrão dos arquivos mime.types.

If strict is True, information will be added to the list of standardtypes, else to the list of non-standard types.

read_windows_registry(strict=True)

Carrega informações do tipo MIME a partir do registro do Windows.

Disponibilidade: Windows.

If strict is True, information will be added to the list of standardtypes, else to the list of non-standard types.

Adicionado na versão 3.2.

mimetypes — Map filenames to MIME types (2024)

FAQs

What are the 7 MIME types? ›

A MIME type consists of two parts: a type and a subtype.

Currently, there are ten registered types: application, audio, example, font, image, message, model, multipart, text, and video.

What are all the file mimetypes? ›

All MIME types
MIMEFile types
application/rsd+xml.rsd
application/rss+xml.rss, .xml
application/rtf.rtf
application/sbml+xml.sbml
243 more rows

What is the MIME file name? ›

A media type (also known as a Multipurpose Internet Mail Extensions or MIME type) indicates the nature and format of a document, file, or assortment of bytes.

What is MIME type mapping? ›

A file's MIME type specifies how a server or browser should interpret the file. For example, whether the file contains plain text, formatted HTML, an image, or a sound recording. In a Web server, MIME mappings specify how a static file should be interpreted by mapping file extensions to MIME types.

What is the most common MIME type? ›

The following two important MIME types are the default types: text/plain is the default value for textual files. A textual file should be human-readable and must not contain binary data. application/octet-stream is the default value for all other cases.

How do I find the MIME type of a file? ›

For detecting MIME-types, use the aptly named "mimetype" command. It has a number of options for formatting the output, it even has an option for backward compatibility to "file". But most of all, it accepts input not only as file, but also via stdin/pipe, so you can avoid temporary files when processing streams.

How many MIME types are there? ›

There are 3059 known MIME types.

What are the MIME types format? ›

A MIME type (also known as a Multipurpose Internet Mail Extension) is a standard that indicates the format of a file. It is a fundamental characteristic of a digital resource that influences its ability to be accessed and used over time.

How to read a MIME file? ›

How to open MIME files
  1. Save the . ...
  2. Launch WinZip from your start menu or Desktop shortcut. ...
  3. Select all the files and folders inside the compressed file. ...
  4. Click 1-click Unzip and choose Unzip to PC or Cloud in the WinZip toolbar under the Unzip/Share tab.

How to create a MIME type file? ›

Steps
  1. Navigate to Protect > Objects > DLP Objects.
  2. Click the green plus icon and select File Mime to create the data pattern.
  3. On the General tab, enter the name and description of the data pattern. ...
  4. Enter the mime type you wish to control for. ...
  5. To save the data pattern, click OK.

What is a filename example? ›

For example, a file created with the name "MyName. Txt" or "myname. txt" would be stored with the filename "MYNAME. TXT".

What is the difference between MIME type and file type? ›

File extensions are hints as to the kind of data the file contains. MIME types are labels for the kind of data in a file. One file extension maps to at most one MIME type.

What are the three types of MIME? ›

It is possible for a skilled mime to combine literal and abstract techniques; an outwardly simple plot is acted out in such a way that deeper meanings are suggested. There are three basic styles in the two types of mime: Oriental, Italian, and French.

How many mime types are there? ›

There are 3059 known MIME types.

What are the 5 rules of mime? ›

The 5 rules are:
  • No talking.
  • Facial expressions.
  • Clear actions.
  • Looking to the audience.
  • Beginning, middle, end.
May 7, 2022

What is the most famous mime? ›

Marcel Marceau was the legendary mime, who survived the Nazi occupation, and saved many children in WWII. He was regarded for his peerless style pantomime, moving audiences without uttering a single word, and was known to the World as a "master of silence."

What is the oldest form of mime? ›

Ancient Greece and Rome

The performance of mime originates at its earliest in Ancient Greece; the name is taken from a single masked dancer called Pantomimus, although performances were not necessarily silent. The first recorded mime was Telestēs in the play Seven Against Thebes by Aeschylus.

References

Top Articles
Latest Posts
Article information

Author: Jonah Leffler

Last Updated:

Views: 5809

Rating: 4.4 / 5 (45 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.