def is_textfile(filename, max_unprintable=0.05): bytes = open(filename).read(512) textchars = ''.join(map(chr, [7,8,9,10,12,13,27] + range(0x20, 0x100))) unprintable = bytes.translate(string.maketrans('',''), textchars) return float(len(unprintable)) / len(bytes) < max_unprintable