之前有写过一个使用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])

实际测试,可以成功转换。

知识点

  1. chardet,这个模块是用来检测编码格式的。检测完成之后返回一个dict类型。dict的key又两个,一个是encode,一个是confidence,参数函数顾名思义。
  2. 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)

可以指定目录,也可以在当前目录下用,递归遍历。

知识点

  1. os.walk,遍历所有文件
  2. os.access,检查文件属性

使用python转换编码格式的更多相关文章

  1. Python 的编码格式

    [前言] Python的编码格式对于初学者来说是很头疼的一件事,不过如果接触的多了,就会发现,只要在恰当的时候使用了恰好的编码,就不会出现太多的问题. [编码介绍] python 的编码格式2.x 和 ...

  2. python转换已转义的字符串

    python转换已转义的字符串 有时我们可能会获取得以下这样的字符串: >>> a = '{\\"name\\":\\"michael\\"} ...

  3. python——代码编码格式转换

    最近刚换工作不久,没太多的时间去整理工作中的东西,大部分时间都在用来熟悉新公司的业务,熟悉他们的代码框架了,最主要的是还有很多新东西要学,我之前主要是做php后台开发的,来这边之后还要把我半路出家的前 ...

  4. Python 爬虫编码格式问题 gb2312转换utf8

    遇到的问题是:爬取网页得到的结果如下(部分)  里面的中文出现乱码. <!DOCTYPE html> <html lang='zh-CN'> <head> < ...

  5. Python: 转换文本编码

    最近在做周报的时候,需要把csv文本中的数据提取出来制作表格后生产图表. 在获取csv文本内容的时候,基本上都是用with open(filename, encoding ='UTF-8') as f ...

  6. python系统编码格式

    python在安装的时候默认的编码格式是ASCII,当程序中出现非ASCII编码时,python的处理常常会报这样的错UnicodeDecodeError,python没办法处理非ASCII编码的,此 ...

  7. python转换html到pdf文件

    1.安装wkhtmltopdf Windows平台直接在 http://wkhtmltopdf.org/downloads.html 下载稳定版的 wkhtmltopdf 进行安装,安装完成之后把该程 ...

  8. windows下用python转换markdown到html

    方法一: 安装markdown, pip install markdown, 安装好后,python -m markdown xxx.md -f xxx.html 方法二:安装markdown2, p ...

  9. protobuf基础类以及python 转换pb2.py文件

    一 protobuf-前端解析js 前端解析思路: 1.问后端要数据模型文件,比如名为MODEL.proto 2.使用谷歌官方的工具生成MODEL.js 3.把项目中引用的MODEL.js 和谷歌官方 ...

随机推荐

  1. Struts2学习记录-Value Stack(值栈)和OGNL表达式

    仅仅是学习记录.把我知道的都说出来 一.值栈的作用 记录处理当前请求的action的数据. 二,小样例 有两个action:Action1和Action2 Action1有两个属性:name和pass ...

  2. 【温故知新】——BABYLON.js学习之路·前辈经验(一)

    前言:公司用BABYLON作为主要的前端引擎,同事们在长时间的项目实践中摸索到有关BABYLON的学习路径和问题解决方法,这里只作为温故知新. 一.快速学习BABYLON 1. 阅读Babylon[基 ...

  3. props default 数组(Array)/对象(Object)的默认值应当由一个工厂函数返回

    1.场景: Object: <!-- 步骤 --> <template> <div> <div class="m-cell"> &l ...

  4. vuex mapState使用

    <template> <div> {{count}} <button @click="handleIncrease">+5</button ...

  5. boost库shared_ptr实现桥接模式

    主程序 /*将抽象部分与实现部分分离,使它们都能够独立的变化*/ #include "bridge.h" int main() { cout <<"main ...

  6. Sql 复习3之存储管理

    一.事务管理 单个工作单元称为事务,我们将若干条sql命令组合在一起,形成存储过程.触发器等,利用存储过程和触发器可以进行事务管理. 二.编程基础介绍 主要有:函数.程序设计语句等. 程序设计语句: ...

  7. 管理voting disks

     管理voting disks 一.关于voting disk 的一些必需要知道的东西: 11g 曾经我们能够使用dd 命令来备份voting disk ,可是在11g 以后 oracle 不再支 ...

  8. linux crontab 定时任务解析

    -----------crontab定时任务---------------------- 检查crontab工具是否安装 crontab -l 检查crontab服务是否启动 service cron ...

  9. 短信计时器Utils

    package com.lvshandian.partylive.utils; import android.content.Context;import android.os.CountDownTi ...

  10. Matlab时频图

    [b,f,t]=specgram(data,nfft,Fs,window,numoverlap); imagesc(t,f,20*log10(abs(b))), axis xy, colormap(j ...