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.
pip install filetypeVerified import paths — ran on the pinned version, not inferred.
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.
Implement a check for `if kind is None:` or similar logic to handle unknown file types gracefully.
Use `try-except FileNotFoundError` blocks to handle missing files, or verify file existence using `os.path.exists()` before calling `guess()`.
Ensure that the buffer passed to `filetype.guess()` contains at least the initial bytes of the file, ideally up to 261 bytes, for reliable type detection.
You need to install the package using pip: `pip install filetype`
Ensure the file is valid and supported. If reading from a buffer, ensure enough bytes are provided. Handle the `None` return gracefully:
```python
import filetype
kind = filetype.guess('path/to/your/file')
if kind is None:
print('File type could not be determined or is not supported.')
else:
print(f'File extension: {kind.extension}')
print(f'File MIME type: {kind.mime}')
```Verify that the file path is correct and that the file exists at the given location. Use an absolute path or ensure the script is run from the correct directory.
```python
import filetype
import os
file_path = 'path/to/correct/file.jpg'
if os.path.exists(file_path):
kind = filetype.guess(file_path)
if kind:
print(f'Detected type: {kind.mime}')
else:
print('File type not recognized.')
else:
print(f'Error: File not found at {file_path}')
```No dependency data recorded yet.