python 读写文件包含多种编码格式的解决方式

yipeiwu_com6年前Python基础

今天写一个脚本文件,需要将多个文件中的内容汇总到一个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设计】。

相关文章

python调用其他文件函数或类的示例

B.py调用A.py的函数或类 在同一个文件夹下 调用函数: A.py文件: def add(x,y): print('和为:%d'%(x+y)) B.py文件: im...

python requests.post带head和body的实例

如下所示: # coding = utf-8 import requests import json host = "http://47.XX.XX.XX:30000" endpo...

python使用MySQLdb访问mysql数据库的方法

本文实例讲述了python使用MySQLdb访问mysql数据库的方法。分享给大家供大家参考。具体如下: #!/usr/bin/python import MySQLdb def d...

python使用selenium实现批量文件下载

python使用selenium实现批量文件下载

背景 实现需求:批量下载联想某型号的全部驱动程序。 一般在做网络爬虫的时候,都是保存网页信息为主,或者下载单个文件。当涉及到多文件批量下载的时候,由于下载所需时间不定,下载的文件名不定,...

python 接收处理外带的参数方法

在执行python 代码的时候,有时候需要传递外面的参数进行处理 这个该怎么实现呢? 需要一个模块 from sys import argv 当然也可以直接只导入 sys im...