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

yipeiwu_com5年前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的Dataframe取两列时间值相差一年的所有行方法

在使用Python处理数据时,经常需要对数据筛选。 这是在对时间筛选时,判断两列时间是否相差一年,如果是,则返回符合条件的所有列。 data原始数据: data[map(lambda...

对python函数签名的方法详解

函数签名对象,表示调用函数的方式,即定义了函数的输入和输出。 在Python中,可以使用标准库inspect的一些方法或类,来操作或创建函数签名。 获取函数签名及参数 使用标准库的sig...

Python通过PIL获取图片主要颜色并和颜色库进行对比的方法

本文实例讲述了Python通过PIL获取图片主要颜色并和颜色库进行对比的方法。分享给大家供大家参考。具体分析如下: 这段代码主要用来从图片提取其主要颜色,类似Goolge和Baidu的图...

python做反被爬保护的方法

网络爬虫,是一个自动提取网页的程序,它为搜索引擎从万维网上下载网页,是搜索引擎的重要组成。但是当网络爬虫被滥用后,互联网上就出现太多同质的东西,原创得不到保护。于是,很多网站开始反网络爬...

基于Python数据可视化利器Matplotlib,绘图入门篇,Pyplot详解

基于Python数据可视化利器Matplotlib,绘图入门篇,Pyplot详解

Pyplot matplotlib.pyplot是一个命令型函数集合,它可以让我们像使用MATLAB一样使用matplotlib。pyplot中的每一个函数都会对画布图像作出相应的改变,...