python 讀寫文件包含多種編碼格式的解決方式
更新時間:2019年12月20日 15:41:00 作者:hm11290219
今天小編就為大家分享一篇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連接Mssql基礎教程之Python庫pymssql
這篇文章主要給大家介紹了關于Python連接Mssql基礎教程之Python庫pymssql的相關資料,文中分別介紹了連接數據庫、游標使用注意事項、游標返回行為字典變量、使用with語句(上下文管理器)以及調用存儲過程等的實現,需要的朋友可以參考下2018-09-09

