How can I detect if a file is binary (non-text) in Python?(如何在 Python 中检测文件是否为二进制(非文本)文件?)
问题描述
如何在 Python 中判断文件是否为二进制(非文本)文件?
How can I tell if a file is binary (non-text) in Python?
我在 Python 中搜索大量文件,并不断在二进制文件中找到匹配项.这使得输出看起来非常混乱.
I am searching through a large set of files in Python, and keep getting matches in binary files. This makes the output look incredibly messy.
我知道我可以使用 grep -I,但我对数据所做的工作超出了 grep 所允许的范围.
I know I could use grep -I, but I am doing more with the data than what grep allows for.
在过去,我只会搜索大于 0x7f 的字符,但 utf8 等在现代系统上是不可能的.理想情况下,解决方案会很快.
In the past, I would have just searched for characters greater than 0x7f, but utf8 and the like, make that impossible on modern systems. Ideally, the solution would be fast.
推荐答案
你也可以使用 mimetypes 模块:
You can also use the mimetypes module:
import mimetypes
...
mime = mimetypes.guess_type(file)
编译二进制mime 类型列表相当容易.例如,Apache 分发了一个 mime.types 文件,您可以将其解析为一组列表、二进制和文本,然后检查 mime 是否在您的文本或二进制列表中.
It's fairly easy to compile a list of binary mime types. For example Apache distributes with a mime.types file that you could parse into a set of lists, binary and text and then check to see if the mime is in your text or binary list.
这篇关于如何在 Python 中检测文件是否为二进制(非文本)文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Python 中检测文件是否为二进制(非文本)文
基础教程推荐
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
