使用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 和谷歌官方 ...
随机推荐
- python tcp,udp简单使用
import socket host = '127.0.0.1' port = 9999 #创建一个tcp socket套接字 tcp_server = socket.socket(socket.AF ...
- 将Solr的数据存到Hdfs上
具体官方文档 https://cwiki.apache.org/confluence/display/solr/Running+Solr+on+HDFS 修改solrconfig.xml文件 < ...
- MySQL监控工具——innotop
MySQL监控工具--innotop innotop是一个mysql数据库实时监控工具,其功能强大,信息种类繁多,很能体现数据库的状态. 它实际上是一个perl脚本,整合show status/sho ...
- 2016.6.20 eclipse中的jsp文件的字体大小在哪里修改
刚打开eclipse的时候,觉得jsp文件的字体太小了.于是去修改字体,但是colors and fonts里的字体选项太多了,不知道哪一个是. 试了几个后发现,是structured text ed ...
- java类中,成员变量赋值第一个进行,其次是静态构造函数,再次是构造函数
如题是结论,如果有人问你Java类的成员初始化顺序和初始化块知识就这样回答他.下面是代码: package com.test; public class TestClass{ // 成员变量赋值第一个 ...
- 【TSQL】空格的比较
空格比较时 空字符串跟任意长度的半角空格字符串比较,结果都为TRUE ) SET @TRUSTOR = '' IF @TRUSTOR IS NULL BEGIN SELECT 'IS NULL' EN ...
- 一款很实用的Memcache监控工具
装了memcahce以后想对使用情况详细了解一下,如分配的内存够不够,都存了什么,经百度后发现这款工具灰常实用!此工具来自Memcache Pecl 中 http://pecl.php.net/pac ...
- struts2实现文件查看、下载
CreateTime--2017年9月7日10:25:33 Author:Marydon struts2实现文件查看.下载 1.界面展示 <a style="color: #199 ...
- 转:DDR中端接技术基本概念
DDR中端接技术基本概念 版权声明:转载请注明出处:http://blog.csdn.net/lg2lh https://blog.csdn.net/lg2lh/article/details/90 ...
- 配置mysql 编码
配置mysql 编码 [client]default-character-set=utf8mb4 default-storage-engine=INNODB [mysql]default-charac ...