如何使用python批量修改文本文件編碼格式
使用python批量修改文本文件編碼格式
把文本文件的編碼格式進(jìn)行批量幻化,比如ascii, gb2312, utf8等,相互轉(zhuǎn)化,字符集的大小來看,utf8>gb2312>ascii,因此最好把gb2312轉(zhuǎn)為utf8,否則容易出現(xiàn)亂碼。
gb2312和utf-8的主要區(qū)別:
關(guān)于字庫規(guī)模: UTF-8 > gb2312(utf8字全而gb2312只有漢字)
關(guān)于保存大小: UTF-8> gb2312 (utf8更臃腫、加載更慢,gb2312更小巧,加載更快)
關(guān)于適用范圍:gb2312主要在中國大陸地區(qū)使用,是一個本地化的字符集,UTF-8包含全世界所有國家需要用到的字符,是國際編碼,通用性強。UTF-8編碼的文字可以在各國支持UTF8字符集的瀏覽器上顯示。
import sys
import chardet
import codecs
def get_encoding_type(fileName):
'''print the encoding format of a txt file '''
with open(fileName, 'rb') as f:
data = f.read()
encoding_type = chardet.detect(data)
#print(encoding_type)
return encoding_type
# such as {'encoding': 'GB2312', 'confidence': 0.99, 'language': 'Chinese'}
def convert_encoding_type(filename_in, filename_out, encode_in="gb2312", encode_out="utf-8"):
'''convert encoding format of txt file '''
#filename_in = 'flash.c'
#filename_out = 'flash_gb2312.c'
#encode_in = 'utf-8' # 輸入文件的編碼類型
#encode_out = 'gb2312'# 輸出文件的編碼類型
with codecs.open(filename=filename_in, mode='r', encoding=encode_in) as fi:
data = fi.read()
with open(filename_out, mode='w', encoding=encode_out) as fo:
fo.write(data)
fo.close()
# with open(filename_out, 'rb') as f:
# data = f.read()
# print(chardet.detect(data))
if __name__=="__main__":
# fileName = argv[1]
# get_encoding_type(fileName)
# convert_encoding_type(fileName, fileName)
filename_of_files = sys.argv[1] #the file contain full file path at each line
with open(filename_of_files, 'rb') as f:
lines = f.readlines()
for line in lines:
fileName = line[:-1]
encoding_type = get_encoding_type(fileName)
if encoding_type['encoding']=='GB2312':
print(encoding_type)
convert_encoding_type(fileName, fileName)
print(fileName)
補充:python實現(xiàn)文件批量轉(zhuǎn)為utf-8格式
python實現(xiàn)文件批量轉(zhuǎn)為utf-8格式
xml_path = './'
with open(xml_path , 'rb+') as f:
?? ?content = f.read()
?? ?codeType = detect(content)['encoding']
?? ?content = content.decode(codeType, "ignore").encode("utf8")
?? ?fp.seek(0)
?? ?fp.write(content)到此這篇關(guān)于如何使用python批量修改文本文件編碼格式的文章就介紹到這了,更多相關(guān)python批量修改文本文件編碼格式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python基于paramunittest模塊實現(xiàn)excl參數(shù)化
這篇文章主要介紹了Python基于paramunittest模塊實現(xiàn)excl參數(shù)化,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04
Python os模塊中的isfile()和isdir()函數(shù)均返回false問題解決方法
這篇文章主要介紹了Python os模塊中的isfile()和isdir()函數(shù)均返回false問題解決方法,返回false的原因是路徑使用了相對路徑,使用絕對路徑就可以解決這個問題,需要的朋友可以參考下2015-02-02
Python入門教程(四十)Python的NumPy數(shù)組創(chuàng)建
這篇文章主要介紹了Python入門教程(四十)Python的NumPy數(shù)組創(chuàng)建,NumPy 用于處理數(shù)組,NumPy 中的數(shù)組對象稱為 ndarray,我們可以使用 array() 函數(shù)創(chuàng)建一個 NumPy ndarray 對象,需要的朋友可以參考下2023-05-05

