栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用Python识别二进制文件和文本文件?[重复]

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用Python识别二进制文件和文本文件?[重复]

谢谢大家,我找到了适合我问题的解决方案。我在http://pre.activestate.com/recipes/173220/上找到了此代码,并做了一些修改以适合我。

它工作正常。

from __future__ import divisionimport stringdef istext(filename):    s=open(filename).read(512)    text_characters = "".join(map(chr, range(32, 127)) + list("nrtb"))    _null_trans = string.maketrans("", "")    if not s:        # Empty files are considered text        return True    if "" 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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660154.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号