鍍金池/ 問答/數(shù)據(jù)分析&挖掘  Python  網(wǎng)絡(luò)安全/ python pandas.dataframe讀取unicode編碼的txt文件

python pandas.dataframe讀取unicode編碼的txt文件出現(xiàn)的問題

我這里擁有一個利用unicode編碼的txt文件,

clipboard.png

當(dāng)我采用下列代碼讀取文件時(代碼中省略了部分文件路徑)

with open('STK_MKT_ValuationMetrics.txt','r') as f:
    pettmInfo = pd.read_table(f)

這種代碼讀取時產(chǎn)生了報(bào)錯:

'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence

然后我分別采用了
1.with open('STK_MKT_ValuationMetrics.txt','rb') as f:
報(bào)錯:'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
2.with open('STK_MKT_ValuationMetrics.txt','rb',encoding='utf-8') as f:
報(bào)錯:binary mode doesn't take an encoding argument
3.with open('STK_MKT_ValuationMetrics.txt','r',encoding='utf-8') as f:
報(bào)錯:'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
無一例外都失敗了,可這都是根據(jù)報(bào)錯一步一步百度搜來的做法。。。。

然后我就把txt文檔另存為utf-8編碼的,再次讀取:

with open('STK_MKT_ValuationMetrics.txt','r',encoding='utf-8') as f:
    pettmInfo = pd.read_table(f)

這時沒有報(bào)錯,但是第一列有些地方以0開頭缺都被省略了,如000006變成了6,這并不是我想要的結(jié)果,如下圖:

clipboard.png

請問這該如何解決呢?如果解答能只對原文件進(jìn)行讀取不改變編碼格式我會覺得更好,實(shí)在不行的話我也就只能手動轉(zhuǎn)化為utf-8讀取了,那么這些省略的0我該如何處理呢?謝謝解答!

回答
編輯回答
怣痛

知乎上有人碰到同樣的問題,答案如下:

#!/usr/bin/python3
# -*- coding:utf8 -*-
import codecs

open("filename",'w',encoding="utf8")
2017年7月2日 14:32
編輯回答
誮惜顏
pd.read_table('filename', sep='分割符', encoding="utf-8", dtype={'列名1': np.列類型1, '列名2': np.列類型2})
2017年8月19日 10:18