使用python转换编码格式
之前有写过一个使用powershell转换文档格式的方法,然而因为powershell支持不是很全,所以并不好用。这里使用python再做一个。
思路
检测源码格式,如果不是utf8,则进行转换,否则跳过
代码
import chardet
import sys
import codecs
def findEncoding(s):
file = open(s, mode='rb')
buf = file.read()
result = chardet.detect(buf)
file.close()
return result['encoding']
def convertEncoding(s):
encoding = findEncoding(s)
if encoding != 'utf-8' and encoding != 'ascii':
print("convert %s%s to utf-8" % (s, encoding))
contents = ''
with codecs.open(s, "r", encoding) as sourceFile:
contents = sourceFile.read()
with codecs.open(s, "w", "utf-8") as targetFile:
targetFile.write(contents)
else:
print("%s encoding is %s ,there is no need to convert" % (s, encoding))
if __name__ == "__main__":
if len(sys.argv) != 2:
print("error filename")
else:
convertEncoding(sys.argv[1])
实际测试,可以成功转换。
知识点
- chardet,这个模块是用来检测编码格式的。检测完成之后返回一个dict类型。dict的key又两个,一个是encode,一个是confidence,参数函数顾名思义。
- with as 这个语法很好用,特别是在打开文件的时候,可以处理忘记关闭文件导致文件一直被占用等异常。
批量转换
import chardet
import sys
import codecs
import os
def findEncoding(s):
file = open(s, mode='rb')
buf = file.read()
result = chardet.detect(buf)
file.close()
return result['encoding']
def convertEncoding(s):
if os.access(s,os.W_OK):
encoding = findEncoding(s)
if encoding != 'utf-8' and encoding != 'ascii':
print("convert %s%s to utf-8" % (s, encoding))
contents = ''
with codecs.open(s, "r", encoding) as sourceFile:
contents = sourceFile.read()
with codecs.open(s, "w", "utf-8") as targetFile:
targetFile.write(contents)
else:
print("%s encoding is %s ,there is no need to convert" % (s, encoding))
else:
print("%s read only" %s)
def getAllFile(path, suffix='.'):
"recursive is enable"
f = os.walk(path)
fpath = []
for root, dir, fname in f:
for name in fname:
if name.endswith(suffix):
fpath.append(os.path.join(root, name))
return fpath
def convertAll(path):
fclist = getAllFile(path, ".c")
fhlist = getAllFile(path, ".h")
flist = fclist + fhlist
for fname in flist:
convertEncoding(fname)
if __name__ == "__main__":
path = ''
if len(sys.argv) == 1:
path = os.getcwd()
elif len(sys.argv) == 2:
path = sys.argv[1]
else:
print("error parameter")
exit()
convertAll(path)
可以指定目录,也可以在当前目录下用,递归遍历。
知识点
- os.walk,遍历所有文件
- os.access,检查文件属性
使用python转换编码格式的更多相关文章
- Python 的编码格式
[前言] Python的编码格式对于初学者来说是很头疼的一件事,不过如果接触的多了,就会发现,只要在恰当的时候使用了恰好的编码,就不会出现太多的问题. [编码介绍] python 的编码格式2.x 和 ...
- python转换已转义的字符串
python转换已转义的字符串 有时我们可能会获取得以下这样的字符串: >>> a = '{\\"name\\":\\"michael\\"} ...
- python——代码编码格式转换
最近刚换工作不久,没太多的时间去整理工作中的东西,大部分时间都在用来熟悉新公司的业务,熟悉他们的代码框架了,最主要的是还有很多新东西要学,我之前主要是做php后台开发的,来这边之后还要把我半路出家的前 ...
- Python 爬虫编码格式问题 gb2312转换utf8
遇到的问题是:爬取网页得到的结果如下(部分) 里面的中文出现乱码. <!DOCTYPE html> <html lang='zh-CN'> <head> < ...
- Python: 转换文本编码
最近在做周报的时候,需要把csv文本中的数据提取出来制作表格后生产图表. 在获取csv文本内容的时候,基本上都是用with open(filename, encoding ='UTF-8') as f ...
- python系统编码格式
python在安装的时候默认的编码格式是ASCII,当程序中出现非ASCII编码时,python的处理常常会报这样的错UnicodeDecodeError,python没办法处理非ASCII编码的,此 ...
- python转换html到pdf文件
1.安装wkhtmltopdf Windows平台直接在 http://wkhtmltopdf.org/downloads.html 下载稳定版的 wkhtmltopdf 进行安装,安装完成之后把该程 ...
- windows下用python转换markdown到html
方法一: 安装markdown, pip install markdown, 安装好后,python -m markdown xxx.md -f xxx.html 方法二:安装markdown2, p ...
- protobuf基础类以及python 转换pb2.py文件
一 protobuf-前端解析js 前端解析思路: 1.问后端要数据模型文件,比如名为MODEL.proto 2.使用谷歌官方的工具生成MODEL.js 3.把项目中引用的MODEL.js 和谷歌官方 ...
随机推荐
- 修改Centos默认源
原文:http://mirrors.aliyun.com/help/centos?spm=5176.bbsr150321.0.0.d6ykiD 1.备份 mv /etc/yum.repos.d/Cen ...
- 【音乐App】—— Vue-music 项目学习笔记:用户个人中心开发
前言:以下内容均为学习慕课网高级实战课程的实践爬坑笔记. 项目github地址:https://github.com/66Web/ljq_vue_music,欢迎Star. 歌曲列表 收藏歌曲 一.用 ...
- AutoIt3常见问题解答
Q1 如何调试脚本? MsgBox(0,"测试",$var) ConsoleWrite("var=" & $var & @CRLF) Q2 ...
- imagemagick imagick
imagemagick#图像处理软件 安装解压 ./configure make make install imagick#是php图像扩展模块 调用imagemagick处理图像 安装解压/opt/ ...
- java thin方式连接oracle数据库
本文主要描述通过thin方式连接oracle数据库 1.创建web project ,将D:\oracle\product\10.2.0\db_1\jdbc\lib(oracle安装目录)下的ojdb ...
- Shell脚本之:while
while循环用于不断执行一系列命令,也用于从输入文件中读取数据:命令通常为测试条件.其格式为: while command do Statement(s) to be executed if com ...
- MySQL -进阶
一.视图 视图是一个虚拟表(非真实存在),其本质是[根据SQL语句获取动态的数据集,并为其命名],用户使用时只需使用[名称]即可获取结果集,并可以将其当作表来使用 SELECT * FROM(SELE ...
- Cocoapods完整使用篇
温馨提示:在篇文章中所使用的Xcode版本为Xcode7. 一.什么是CocoaPods? 简单来说,就是专门为iOS工程提供对第三方库的依赖的管理工具,通过CocoaPods,我们可以单独管理每 ...
- openwrt patch
一: 这几天使用一款电信的4G网卡,发现了一些问题,所以决定打个pitch来解决问题,顺便把patch的生成与使用学习一下 二:安装patch的管理工具quilt 1. sudo apt-get in ...
- EF6&EFCore 注册/使用实体类的正确姿势
首先回顾下EF中常规使用流程 1.新建实体类以及实体配置(data annotation或fluent api) [Table("Users")] public class Use ...