import chardet
import os def strJudgeCode(str):
return chardet.detect(str) def readFile(path):
try:
f = open(path, 'r')
filecontent = f.read()
finally:
if f:
f.close() return filecontent def WriteFile(str, path):
try:
f = open(path, 'w')
f.write(str)
finally:
if f:
f.close() def converCode(path):
file_con = readFile(path)
result = strJudgeCode(file_con)
#print(file_con)
if result['encoding'] == 'utf-8':
#os.remove(path)
a_unicode = file_con.decode('utf-8')
gb2312 = a_unicode.encode('gbk')
WriteFile(gb2312, path) def listDirFile(dir):
list = os.listdir(dir)
for line in list:
filepath = os.path.join(dir, line)
if os.path.isdir(filepath):
listDirFile(filepath)
else:
print(line)
converCode(filepath) if __name__ == '__main__':
listDirFile(u'.\TRMD')

详细解释:


 1 import chardet
import os def strJudgeCode(str):
return chardet.detect(str)
'''
chardet.detect()返回字典,其中confidence是检测精确度,encoding是编码形式
{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}
()网页编码判断: >>> import urllib
>>> rawdata = urllib.urlopen('http://www.google.cn/').read()
>>> import chardet
>>> chardet.detect(rawdata)
{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}
()文件编码判断 复制代码
import chardet
tt=open('c:\\111.txt','rb')
ff=tt.readline()
#这里试着换成read()也可以,但是换成readlines()后报错
enc=chardet.detect(ff)
print enc['encoding']
tt.close()
''' def readFile(path):
try:
f = open(path, 'r')
filecontent = f.read()
finally:
if f:
f.close() return filecontent def WriteFile(str, path):
try:
f = open(path, 'w')
f.write(str)
finally:
if f:
f.close() def converCode(path):
file_con = readFile(path)
result = strJudgeCode(file_con)
#print(file_con)
if result['encoding'] == 'utf-8':
#os.remove(path)
a_unicode = file_con.decode('utf-8')
'''
使用decode()和encode()来进行解码和编码
u = '中文' #指定字符串类型对象u
str = u.encode('gb2312') #以gb2312编码对u进行编码,获得bytes类型对象str
u1 = str.decode('gb2312')#以gb2312编码对字符串str进行解码,获得字符串类型对象u1
u2 = str.decode('utf-8')#如果以utf-8的编码对str进行解码得到的结果,将无法还原原来的字符串内容
'''
gb2312 = a_unicode.encode('gbk')
WriteFile(gb2312, path) def listDirFile(dir):
list = os.listdir(dir)#返回指定路径下的文件和文件夹列表。
for line in list:
filepath = os.path.join(dir, line)
'''
是在拼接路径的时候用的。举个例子,
os.path.join(“home”, "me", "mywork")
在Linux系统上会返回
“home/me/mywork"
在Windows系统上会返回
"home\me\mywork"
好处是可以根据系统自动选择正确的路径分隔符"/"或"\"
'''
if os.path.isdir(filepath):#os.path.isdir()函数判断某一路径是否为目录
listDirFile(filepath)
else:
print(line)
converCode(filepath) if __name__ == '__main__':
listDirFile(u'.\TRMD')
'''
u'string' 表示 已经是 unicode 编码的 'string' 字符串
# -*- coding: UTF- -*- 这句是告诉python程序中的文本是utf-8编码,让python可以按照utf-8读取程
中文前加u就是告诉python后面的是个unicode编码,存储时按unicode格式存储。
'''

python 修改文件编码方式的更多相关文章

  1. python批量修改文件内容及文件编码方式的处理

    最近公司在做tfs迁移,后面要用新的ip地址去访问tfs 拉取代码  ,所以原来发布脚本中.bat类型的脚本中的的ip地址需要更换 简单说下我们发布脚本层级目录 :每个服务站点下都会有一个发布脚本 . ...

  2. 格式化MyEclipse代码(java、jsp、js)行的长度@修改java代码字体@修改Properties文件编码方式

    每次用MyEclipse/Eclipse自带的快捷键Ctrl+shift+f格式化代码时,如果原来的一行代码大于80列,Eclipse就会自动换为多行.如果想格式化代码后不想让代码换行可以通过以下方式 ...

  3. Python读取文件编码及内容

    Python读取文件编码及内容 最近做一个项目,需要读取文件内容,但是文件的编码方式有可能都不一样.有的使用GBK,有的使用UTF8.所以在不正确读取的时候会出现如下错误: UnicodeDecode ...

  4. python 修改文件内容

    python 修改文件内容 一.修改原文件方式 1 def alter(file,old_str,new_str): 2 """ 3 替换文件中的字符串 4 :param ...

  5. python 的文件编码处理

    python的文件编码处理有点粗鲁 1.不管文件原来是编码类型,读入后都转换成Unicode的编码 2.写入文件时,write函数把变量以读入文件的编码方式写入(根据open(path,mode,en ...

  6. Ubuntu 查看/修改文件编码

    使用enca工具可以查看和修改文件编码 1.安装 sudo apt-get install enca 2.使用 查看文件编码 enca –L zh_CN file_name 修改文件编码 enca – ...

  7. eclipse修改文件编码

    http://topic.csdn.net/u/20080724/14/428de399-790d-442a-8340-3a5fb6dcfcee.html[修改文件编码,假设JS]   在Eclips ...

  8. 分享一个批量修改文件编码的python脚本

    分享一个自己编写的递归查找子目录,将所有cpp文件编码修改为utf-8编码格式的小脚本 #i!/usr/bin/env python3 # -*- coding:utf-8 -*- import os ...

  9. Python中文件编码的检测

    前言: 文件打开的原则是“ 以什么编码格式保存的,就以什么编码格式打开 ”,我们常见的文件一般是以“ utf-8 ”或“ GBK ”编码进行保存的,由于编辑器一般设置了默认的保存和打开方式,所以我们在 ...

随机推荐

  1. WDA-BOPF业务对象处理框架

    SAP中的BOPF(Business Object Processing Framework) 正文 希望简化你的业务应用开发过程?业务对象处理框架(Business Object Processin ...

  2. UI5-文档-4.3-Controls

    现在是时候构建我们的第一个小UI了,将HTML主体中的“Hello World”文本替换为SAPUI5控件sap.m.Text.首先,我们将使用JavaScript控件接口来设置UI,然后将控件实例放 ...

  3. YAML描述与Python的对应关系

    YAML是"YAML Ain't a Markup Language"的首字母缩写,其语法简单,结构通过空格来展示,(列表)项目使用"-"来代表,(字典)键值对 ...

  4. Spoon新建repository的时候

    Spoon新建repository的时候,下面选项选择‘否’,不要选择‘是’,不然可能会出错.

  5. Haskell语言学习笔记(60)Biapplicative

    Biapplicative class Bifunctor p => Biapplicative p where bipure :: a -> b -> p a b (<< ...

  6. jsp页面重定向

    <%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncodi ...

  7. sudoers的权限被改,又忘记了root密码,又不能重启。这么做。

    报下面这个错 sudo: /etc/sudoers is world writablesudo: no valid sudoers sources found, quittingsudo: unabl ...

  8. EasyUI 删除

    <script type="text/javascript"> <!-- js --> /*================================ ...

  9. JPA子查询

    Subquery<A> subquery = criteriaQuery.subquery(A.class); Root<A> root1 = subquery.from(A. ...

  10. Android中MD5加密

    最近项目中遇到MD5加密,代码很简单,又是死代码,不过要注意当长度不足32的时候要补个0.下面是具体代码,直接拷贝就能用. public static String getMD5(String str ...