如何解决如何使用Python识别二进制文件和文本文件?
谢谢大家,我找到了适合我问题的解决方案。我在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
解决方法
我需要确定哪个 文件 是 二进制文件 ,哪个是目录中的 文本 。
我尝试使用 mimetypes,
但在我看来,这不是一个好主意,因为它无法识别所有文件mime,并且在这里有陌生人…我只需要知道二进制或文本即可。简单吗?但我找不到解决方案…
谢谢
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。