使用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 和谷歌官方 ...
随机推荐
- (转)ubuntu/var/log/下各个日志文件
本文简单介绍ubuntu/var/log/下各个日志文件,方便出现错误的时候查询相应的log /var/log/alternatives.log-更新替代信息都记录在这个文件中 /var/log/ ...
- 2016.11.4 Injection of autowired dependencies failed
运行项目时,提示错误: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ' ...
- MySQL5.6安装图解(windows7/8_64位)
这篇文章主要内容是关于MySQL5.6安装图解,希望通过这篇文章顺利解决大家安装MySQL5.6的问题,再也不用为了安装烦恼. 1. 下载MySQL2. 解压MySQL压缩包将以下载的MySQL压缩包 ...
- java8新特性学习笔记(二) 流的相关思想
流是什么 流是Java API的新成员,他允许你以声明的方式处理数据集合,就现在来说,可以把他们看成遍历数据集合的高级迭代器.此外,流还可以透明地并行处理,你无须写任何多线程代码. 下面例子是新老AP ...
- UISegmentedControl的具体使用
当用户输入不不过布尔值时.可使用分段控件(UISegmentedControl).分段控件提供一栏button(有时称为button栏),但只能激活当中一个button. 分段控件会导致用户在屏幕上看 ...
- Android MarginLeft与MarginStart的差别
在写layout布局的时候,我们会发现有这样几个比較相似的属性: MarginStart MarginLeft MarginEnd MarginRight 这些属性的差别是什么? 依据ap ...
- 字符串== equals
经常碰到比较字符串的题, eg: public class StringDemo{ private static final String MESSAGE = "taobao"; ...
- Attribute "resultType" must be declared for element type "insert".
这是mybatis插入数据库之后出现的问题,至于为什么出现这个问题,是因为插入的时候你照抄了查询的语句,插入的时候只有id属性和parameterType属性,并没有“resultType”属性,要注 ...
- Android - 单例模式(singleton)的使用
单例模式(singleton)的使用 本文地址:http://blog.csdn.net/caroline_wendy 单例(singleton)是特殊的Java类,在创建实例时.一个类仅同意创建一个 ...
- modelsim-altera IP核仿真
modelsim 仿真fifo时出现 Instantiation of 'scfifo' failed. The design unit was not found. 2012-07-21 13:27 ...