python设置文件编码_python批量修改文件编码格式的方法
本文實例為大家分享了python批量修改文件編碼格式的具體代碼,供大家參考,具體內容如下
使用說明:
1、使用工具:Python2.7.6+chardet2.3.0,chardet2.3.0下載地址:點擊這里
2、環(huán)境配置:Python安裝+配置環(huán)境變量,chardet解壓放在Python安裝目錄\Lib\site-packages下
舉例:批量修改當前路徑下所有.cpp文件的編碼格式為UTF-8,代碼如下:
python:
import os
import sys
import codecs
import chardet
def convert(filename,out_enc="UTF-8"):
try:
content=codecs.open(filename,'r').read()
source_encoding=chardet.detect(content)['encoding']
print source_encoding
content=content.decode(source_encoding).encode(out_enc)
codecs.open(filename,'w').write(content)
except IOError as err:
print("I/O error:{0}".format(err))
def explore(dir):
for root,dirs,files in os.walk(dir):
for file in files:
if os.path.splitext(file)[1]=='.cpp':
print file
path=os.path.join(root,file)
convert(path)
def main():
explore(os.getcwd())
if __name__=="__main__":
main()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
總結
以上是生活随笔為你收集整理的python设置文件编码_python批量修改文件编码格式的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python怎么控制速度_如何控制pyt
- 下一篇: python资源管理器选择文件_Pyth