Tho*_*mas 11
谢谢大家,我找到了适合我的问题的解决方案.我在http://code.activestate.com/recipes/173220/上找到了这个代码,我改变了一小块以适合我.
它工作正常.
from __future__ import division
import string
def istext(filename):
s=open(filename).read(512)
text_characters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b"))
_null_trans = string.maketrans("", "")
if not s:
# Empty files are considered text
return True
if "\0" in s:
# Files with null bytes are likely binary
return False
# Get the non-text characters (maps a character to itself then
# use the 'remove' option to get rid of the text characters.)
t = s.translate(_null_trans, text_characters)
# If more than 30% non-text characters, then
# this is considered a binary file
if float(len(t))/float(len(s)) > 0.30:
return False
return True
Run Code Online (Sandbox Code Playgroud)
这本质上并不简单.虽然在大多数情况下你可以采取一个相当好的猜测,但没有办法确定.
你可能想做的事情:
但它是所有启发式的 - 例如,很可能有一个文件是有效的文本文件和有效的图像文件.作为一个文本文件可能是无稽之谈,但在某些编码或其他方面合法......
如果您的脚本在 *nix 上运行,您可以使用以下内容:
import subprocess
import re
def is_text(fn):
msg = subprocess.Popen(["file", fn], stdout=subprocess.PIPE).communicate()[0]
return re.search('text', msg) != None
Run Code Online (Sandbox Code Playgroud)