Python使用chardet包自动检测编码
2017-08-02 08:56
459 查看
chardet:charset detection
一旦自动检测出编码,就可以解码了。
r:只读方式打开
a:追加方式打开
r+:先读后写
以上四种打开方式加上b,表示二进制方式。
strict:默认,抛出异常
replace:替换
ignore:不管
utf.py
一旦自动检测出编码,就可以解码了。
八种文件打开方式
w:一旦打开文件,文件内容就清空了r:只读方式打开
a:追加方式打开
r+:先读后写
以上四种打开方式加上b,表示二进制方式。
str.decoding(encoding,error='strice')
解码时遇到错误有三种处理方式strict:默认,抛出异常
replace:替换
ignore:不管
utf.py
import chardet import os import sys def utf(path, recursive=False): print(path) if os.path.isfile(path): with open(path, 'rb+') as f: content = f.read() encoding = chardet.detect(content)['encoding'] if encoding != 'utf-8': s = content.decode(encoding, errors='ignore') f.write(s.encode('utf8', errors='ignore')) else: for i in os.listdir(path): now_path = os.path.join(path, i) if os.path.isdir(now_path) and recursive: utf(now_path, recursive) elif os.path.splitext(i)[1] == '.txt': utf(now_path) usage = """ python utf haha.txt #更改单文件 python utf haha #更改文件夹下的全部文本文件(.txt) python utf haha recursive #递归更改文件夹下的全部文本文件 """ if __name__ == '__main__': # sys.argv = ['main', r'C:\Users\weidiao\Desktop\电子书', 'recursive'] if len(sys.argv) == 1: print(usage) exit() if len(sys.argv) > 3: print(usage) print('too many argument') exit() path = sys.argv[1] if not os.path.exists(sys.argv[1]): print(usage) print('no this file or folder') exit() recursive = (len(sys.argv) == 3 and sys.argv[2] == 'recursive') utf(path, recursive)
相关文章推荐
- Python使用chardet包自动检测编码
- Python中动态检测编码chardet的使用教程
- 【整理】Python的字符编码检测库:charade和chardet的区别
- python判断字符串编码的简单实现方法(使用chardet)
- python使用chardet判断字符串编码的方法
- 【教程】如何用Python中的chardet去检测字符编码类型
- Python编码检测 chardet 效果不如 UnicodeDammit
- python判断字符串编码的简单实现方法(使用chardet)
- python编码检测模块chardet
- Python基础 检测多种语言编码 chardet
- python3下的编码检测——chardet
- python模块使用之chardet, 判断字符串编码
- 使用python实现自动“扫描检测硬件改动”功能
- python判断字符串编码——使用chardet判断字符串编码的方法
- python2.7:文件编码检测chardet 详解
- Python之动态检测编码chardet
- python使用chardet判断字符串编码的方法
- python3下的编码检测——chardet
- python chardet模块 检测文档编码
- 使用setuptools自动安装python模块