Filetype Inference Library

1.2.0 · active · verified Sun Mar 29

Small and dependency-free Python package to infer file type and MIME type by checking the magic numbers signature of a file or buffer. It is a Python port from the 'filetype' Go package, offering a simple and friendly API for a wide range of file types. Currently at version 1.2.0, it is actively maintained with periodic updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `filetype.guess()` to infer the type of a file based on its path and from a bytes buffer. It creates a dummy JPEG file to showcase the functionality and then cleans it up. The library returns a `Kind` object with `extension` and `mime` attributes, or `None` if the type cannot be determined.

import filetype
import os

# Create a dummy JPEG file for demonstration
dummy_jpeg_path = 'dummy.jpg'
# A minimal JPEG header (first few bytes of a typical JPEG file)
# In a real scenario, you'd read from an actual file.
jpeg_magic_bytes = b'\xFF\xD8\xFF\xE0\x00\x10\x4A\x46\x49\x46\x00\x01'

try:
    with open(dummy_jpeg_path, 'wb') as f:
        f.write(jpeg_magic_bytes)

    # Guess the file type from the path
    kind = filetype.guess(dummy_jpeg_path)

    if kind is None:
        print('Cannot guess file type!')
    else:
        print(f'File extension: {kind.extension}')
        print(f'File MIME type: {kind.mime}')

    # You can also guess from a buffer/bytes object
    kind_from_buffer = filetype.guess(jpeg_magic_bytes)
    if kind_from_buffer:
        print(f'Buffer extension: {kind_from_buffer.extension}')
        print(f'Buffer MIME type: {kind_from_buffer.mime}')

finally:
    # Clean up the dummy file
    if os.path.exists(dummy_jpeg_path):
        os.remove(dummy_jpeg_path)

view raw JSON →