2017-03-04 97 views
2

我试图从压缩归档中将文本文件读入Pandas数据框。该文件的格式是这样的:将固定宽度的文本文件从zipfiles读取到Pandas数据框中

System Time  hh:mm:ss   PPS  Zsec(sec)   Hex Message 

Yr=17 Mn= 3 Dy= 3 

19:22:59.894  19:22:16  52   69736  7E 32 02 4F 02 00 0C 7F 97 68 10 01 00 11 03 03 13 16 10 34 00 00 00 05 02 00 80 00 83 B1 7E 
19:24:12.130  19:23:10  106   69790  7E 32 02 4F 02 00 0C 7F 97 9E 10 01 00 11 03 03 13 17 0A 6A 00 00 00 05 12 00 BA 00 47 DF 7E 
19:24:13.241  19:23:11  107   69791  7E 32 02 4F 02 00 0C 7F 97 9F 10 01 00 11 03 03 13 17 0B 6B 00 00 00 05 05 00 BC 00 F3 AC 7E 

如果文件归档外提取的,我可以读取它:

data = '../data/test1/heartbeat.txt' 
df = pd.read_csv(data, sep='\s{2,}', engine='python', skiprows=4, encoding='utf8', 
       names=['System Time','hh:mm:ss','PPS','Zsec(sec)', 'Hex Message']) 

但是,如果我尝试访问它的压缩文件内部的方法未能:

zf = zipfile.ZipFile('../data.zip', 'r') 
data = zf.open('data/test1/heartbeat.txt') 
df = pd.read_csv(data, sep='\s{2,}', engine='python', skiprows=4, encoding='utf8', 
       names=['System Time','hh:mm:ss','PPS','Zsec(sec)', 'Hex Message']) 

我看TypeError: cannot use a string pattern on a bytes-like object

如果我使用delim_whitespace代替\s{2,}它读取文件。所以看起来我正在成功使用zipfile。但是,“十六进制消息”列包含单个空格,这些空格会分解为数据框中的许多列。

我用固定宽度列读取,read_fwf,这还与提取的文件也尝试:

data = '../data/test1/heartbeat.txt' 
widths = [13,14,10,13,100] 
df = pd.read_fwf(data,widths=widths,skiprows=4, 
       names = ['System Time', 'hh:mm:ss', 'PPS', 'Zsec(sec)','Hex Message']) 

但是当文件是zip压缩包里面还是失败:TypeError: a bytes-like object is required, not 'str'

我不确定如何将这些类似字节的对象从zip文件转换为Pandas阅读器可以解析的东西。

回答

2

这是为我工作:

zf = zipfile.ZipFile('../data.zip', 'r') 
data = io.StringIO(zf.read('data/test1/heartbeat.txt').decode('utf_8')) 
df = pd.read_csv(data, sep='\s{2,}', engine='python', skiprows=4, encoding='utf8', 
       names=['System Time','hh:mm:ss','PPS','Zsec(sec)', 'Hex Message']) 
+1

刚发现'''io.TextIOWrapper'''我更喜欢。 – nlsn

相关问题