python获取文件编码格式除了chardet还有别的方式吗_使用python的chardet库获得文件编码并修改编码...
首先需要安裝chardet庫(kù),有很多方式,我才用的是比較笨的方式:sudo pip install chardet
#!/usr/bin/env python
# coding: UTF-8
import sys
import os
import chardet
def print_usage():
print '''usage:
change_charset [file|directory] [charset] [output file]\n
for example:
change 1.txt utf-8 n1.txt
change 1.txt utf-8
change . utf-8
change 1.txt
'''
def get_charset(s):
return chardet.detect(s)['encoding']
def remove(file_name):
os.remove(file_name)
def change_file_charset(file_name,output_file_name,charset):
f = open(file_name)
s = f.read()
f.close()
if file_name == output_file_name or output_file_name == "":
remove(file_name)
old_charset = get_charset(s)
u = s.decode(old_charset)
if output_file_name == "":
output_file_name = file_name
f = open(output_file_name,'w')
s = u.encode(charset)
f.write(s)
f.close()
def do(file_name,charset):
if os.path.isdir(file_name):
for item in os.listdir(file_name):
try:
if os.path.isdir(file_name+"/"+item):
do(file_name+"/"+item,"",charset)
else:
change_file_charset(file_name+"/"+item,charset)
except OSError,e:
print e
else:
change_file_charset(file_name,charset)
if __name__ == '__main__':
length = len(sys.argv)
if length == 1:
print_usage()
elif length == 2:
do(sys.argv[1],"utf-8")
elif length == 3:
do(sys.argv[1],sys.argv[2])
elif length == 4:
do(sys.argv[1],sys.argv[3],sys.argv[2])
else:
print_usage()
總結(jié)
如果覺(jué)得編程之家網(wǎng)站內(nèi)容還不錯(cuò),歡迎將編程之家網(wǎng)站推薦給程序員好友。
本圖文內(nèi)容來(lái)源于網(wǎng)友網(wǎng)絡(luò)收集整理提供,作為學(xué)習(xí)參考使用,版權(quán)屬于原作者。
如您喜歡交流學(xué)習(xí)經(jīng)驗(yàn),點(diǎn)擊鏈接加入交流1群:1065694478(已滿(mǎn))交流2群:163560250
總結(jié)
以上是生活随笔為你收集整理的python获取文件编码格式除了chardet还有别的方式吗_使用python的chardet库获得文件编码并修改编码...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: mac mysql 连接超时时间设置_M
- 下一篇: ecshop清除mysql缓存_禁用ec