Skip to content

Instantly share code, notes, and snippets.

@lyhapple
Created June 30, 2014 04:26
Show Gist options
  • Save lyhapple/33644b742d62b06c894c to your computer and use it in GitHub Desktop.
Save lyhapple/33644b742d62b06c894c to your computer and use it in GitHub Desktop.
尝试转换文件编码,默认转换成utf-8编码
#coding=utf-8
import codecs
import os
import shutil
import chardet
def convert_encoding(file_path, target_encoding="utf-8"):
"""
尝试转换文件编码,默认转换成utf-8编码
:param file_path:
:param target_encoding:
"""
#TODO:提示:需要安装python的chardet库
back_file = file_path + '.bak'
try:
shutil.copyfile(file_path, back_file)
content = codecs.open(file_path, 'r').read()
source_encoding = chardet.detect(content)['encoding']
if str(source_encoding).lower() != target_encoding:
content = content.decode(source_encoding)
codecs.open(file_path, 'w', encoding=target_encoding).write(content)
return True
except:
try:
os.remove(file_path)
os.rename(back_file, file_path)
except:
pass
return False
if __name__ == "__main__":
print convert_encoding("/home/lyh/ln.txt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment