is_binary_file (main)

mantis · files, file-type-detection, byte-scanning

Checks if a file is binary by detecting null bytes in its initial block, treating read errors as binary.

def is_binary_file(path: Path, block_size: int = 1024) -> bool:
    """Returns True if the file contains null bytes in its initial block."""
    try:
        with open(path, "rb") as f:
            return b"\x00" in f.read(block_size)
    except OSError:
        return True

See the full source, get the GitHub permalink, and search 40K more like it.

Get a free API key