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
可以使用libmagic来猜测使用python-magic的文件的MIME类型。如果您在"text/*"名称空间中返回了某个内容,则它可能是文本文件,而其他内容可能是binary file。
它本质上是而不是简单的。虽然在大多数情况下你都能做出相当好的猜测,但无法确定。
你可能想做的事情:
但这都是启发性的——例如,很有可能有一个有效的文本文件和的有效图像文件。作为一个文本文件,这可能是无稽之谈,但在某些编码或其他方面是合法的。。。
谢谢大家,我找到了一个适合我的问题的解决方案。我在http://code.activestate.com/recipes/173220/找到了这段代码,为了适应我,我只修改了一小段。
它工作得很好。
相关问题 更多 >
编程相关推荐