def istext(filename):
    s = open(filename).read(512)
text_characters = ''.join(map(chr, list(range(32, 127))) + list('\n\r\t\x08'))
_null_trans = string.maketrans('', '')
if not s:
    return True
if '\x00' in s:
    return False
How to identify binary and text files using Python?