首页 技术 正文
技术 2022年11月23日
0 收藏 501 点赞 4,578 浏览 1101 个字

chardet:charset detection

一旦自动检测出编码,就可以解码了。

八种文件打开方式

  • w:一旦打开文件,文件内容就清空了
  • r:只读方式打开
  • a:追加方式打开
  • r+:先读后写

    以上四种打开方式加上b,表示二进制方式。

str.decoding(encoding,error=’strice’)

解码时遇到错误有三种处理方式

  • strict:默认,抛出异常
  • replace:替换
  • ignore:不管

utf.py

import chardet
import os
import sysdef 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开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,030
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,859