把文字檔案的編碼格式進行批次幻化,例如ascii, gb2312, utf8等,相互轉化,字元集的大小來看,utf8>gb2312>ascii ,因此最好把gb2312轉為utf8,否則容易出現亂碼。
gb2312與utf-8的主要差異:
##關於字庫規模:UTF-8 > gb2312(utf8字全而gb2312只有漢字)
關於保存大小: UTF-8> gb2312(utf8更臃腫、加載更慢,gb2312更小巧,加載更快)
#關於適用範圍: gb2312主要在中國大陸地區使用,是一個本地化的字符集,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實作檔案批次轉為utf-8格式python實作檔案批次轉為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)
以上是怎麼使用python批次修改文字檔編碼格式的詳細內容。更多資訊請關注PHP中文網其他相關文章!