【发布时间】:2017-03-04 16:00:23
【问题描述】:
我正在尝试从压缩存档中将文本文件读入 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'])
但如果我尝试在 zipfile 中访问它,这种方法会失败:
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'
我不确定如何将这些字节状对象从 zipfile 转换为 Pandas 阅读器可以解析的内容。
【问题讨论】:
标签: python python-3.x pandas zipfile