Python处理多编码文件读写错误的解决方案

巷口听风
巷口听风
发布时间:2026-10-12 | 2人浏览过
原创

本文介绍在Python中汇总多个不同编码格式文件时遇到的读写错误问题。通过结合chardet库自动检测编码,并针对UTF-8、GB2312及UTF-8-SIG等格式采取差异化读取策略,成功解决编码冲突。文中提供了完整的代码示例,展示如何遍历目录、识别编码并统一写入结果文件,适用于需要批量处理混合编码文本数据的场景。

在编写脚本以将多个文件内容汇总至单个txt文件时,若源文件包含三种不同的编码格式,直接读写会引发错误。此处记录一种有效的解决方法:

# -*- coding: utf-8 -*-
import wave
import pylab as pl
import numpy as np
import pandas as pd
import os
import time
import datetime
import arrow
import chardet
import sys 
reload(sys) 
sys.setdefaultencoding('utf8') 
os.chdir("F:/new_srt")


#get words of srt file
###########################################
def get_word():
 path = "F:/new_srt"
 filelist = os.listdir(path)
 for files in filelist:
  print files
  encoding = chardet.detect(open(files,'r').read())['encoding']
  if encoding == 'utf-8':
   data=pd.read_csv(files,encoding="utf-8",sep='\r',header=None)
  elif encoding == 'GB2312':
   try:
    data=pd.read_csv(files,encoding="gbk",sep='\r',header=None)
   except UnicodeDecodeError:
    data=pd.read_csv(files,encoding="utf-8",sep='\r',header=None)
  elif encoding == 'UTF-8-SIG':
   data=pd.read_csv(files,encoding="UTF-8-SIG",sep='\r',header=None)
  else:
   print 'this is an error about %s' % files 

  data_new=pd.DataFrame(np.reshape(data.values, (-1,3)))
  data_new.columns=['index','timecut','content']
  filename = os.path.splitext(files)[0]  #filetype = os.path.splitext(files)[1]
  with open('F:/result.txt', 'a') as file:
   file.write(str(filename)+' ' )
   for item in data_new['content']:
    file.write(item.decode("utf-8") +' ') #s=s.decode("utf-8") 
   file.write('\n')


if __name__ == '__main__':
 get_word()

上述关于Python处理多编码文件读写的解决方案即为全部内容,供参考。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表