Python处理文件的方法(mimetypes和chardet)
作者:八戒无戒i
处理文件时minetype和chardet是很好用的两个模块函数:
###chardet:
主要处理文件文件编码问题

假如有这个一个配置文件,非ascii或者utf8编码:
__coding__ = 'UTF-8'
__author__ = 'bingo'
import chardet
import configparser
parse = configparser.ConfigParser()
parse.read("config.ini")
print(parse.sections())
运行结果:
G:\Anaconda\python.exe "C:/Users/bingo/Desktop/The crawler/学习/demo.py"
Traceback (most recent call last):
File "C:/Users/bingo/Desktop/The crawler/学习/demo.py", line 29, in <module>
parse.read("config.ini")
File "G:\Anaconda\lib\configparser.py", line 696, in read
self._read(fp, filename)
File "G:\Anaconda\lib\configparser.py", line 1014, in _read
for lineno, line in enumerate(fp, start=1):
UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal >multibyte sequence
但是改成下面, 用chardet先获取文件编码格式,就可以完美解决上面报错问题:
import chardet
import configparser
data = open("config.ini", "rb").read()
a = chardet.detect(data)
print(a)
parse = configparser.ConfigParser()
parse.read("config.ini", encoding=a["encoding"])
print(parse.sections())
>>>>>>>>>>>>>>>再运行:
G:\Anaconda\python.exe "C:/Users/bingo/Desktop/The crawler/学习/demo.py"
{'encoding': 'UTF-16', 'confidence': 1.0, 'language': ''}
['config']
Process finished with exit code 0
###mimetypes:
主要处理文件文件类型问题
该模块提供在文件名或URL与与文件扩展名关联的MIME类型之间进行转换的功能,主要有以下两个函数:
mimetypes.guess_type(url, strict=True):
返回一个元组(type, encoding), strict默认参数,指定已知MIME类型的列表是否仅限于在IANA注册的官方类型,type为MIME类型,encoding可能为None
mimetypes.guess_all_extensions(type, strict=True):
返回一个列表,根据传入的type(MIME类型),返回提供所有可能的文件扩展名的字符串列表,包括前导点('.'),strict默认参数,指定已知MIME类型的列表是否仅限于在IANA注册的官方类型
import mimetypes
# 获取文件MIME类型
type, encoding = mimetypes.guess_type("demo.py")
print(type)
# 根据MIME类型获取所有可能的文件后缀名
c = mimetypes.guess_all_extensions(type)
print(c)
>>>运行结果如下:
G:\Anaconda\python.exe "C:/Users/bingo/Desktop/The crawler/学习/demo.py"
text/plain
['.bat', '.c', '.h', '.ksh', '.pl', '.txt', '.asm', '.cc', '.cod', '.cpp', '.cs', '.csh', '.cshader', >'.csproj', '.cxx', '.def', '.dsh', '.dshader', '.dsp', '.dsw', '.efu', '.filters', '.fx', '.gitattributes', >'.gitignore', '.gitmodules', '.gsh', '.gshader', '.hh', '.hlsl', '.hlsli', '.hpp', '.hsh', '.hshader', >'.hxx', '.i', '.idl', '.inc', '.inl', '.ipp', '.js', '.jsproj', '.jsx', '.jsxbin', '.jsxinc', '.lst', '.mak', >'.map', '.mdp', '.mk', '.odh', '.odl', '.pkgdef', '.pkgundef', '.psh', '.pshader', '.py', '.pyw', >'.rc', '.rc2', '.rct', '.res', '.rgs', '.s', '.sln', '.sol', '.sor', '.srf', '.tlh', '.tli', '.ts', '.tsx', '.tt', >'.user', '.vb', '.vbproj', '.vcp', '.vcw', '.vsh', '.vshader']
.bat
Process finished with exit code 0
到此这篇关于Python—处理文件(mimetypes和chardet)的文章就介绍到这了,更多相关Python—处理文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
