嗨,我正在尝试将.dat文件转换为。 CSV,但即时通讯无法。请耐心等待,因为我仍然是python的初学者。
这是我的代码:
import pandas as pd
from io import StringIO
with open('blk01530.dat','r') as f:
df = pd.DataFrame(l.rstrip().split() for l in f)
print(df)
这是我遇到的错误
Traceback (most recent call last):
File "/Users/sunqinan/Desktop/FYP/convertdat.py", line 5, in <module>
df = pd.DataFrame(l.rstrip().split() for l in f)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pandas/core/frame.py", line 445, in __init__
data = list(data)
File "/Users/sunqinan/Desktop/FYP/convertdat.py", line 5, in <genexpr>
df = pd.DataFrame(l.rstrip().split() for l in f)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf9 in position 0: invalid start byte
请帮忙,因为我已经尝试了几个小时,这就是我的.dat文件的样子
1 f9be b4d9 4243 1300 0000 0020 5f7f ef93
2 ff4f 1dc9 dd08 3798 9dbe f46a 2b6d 1b8c
3 2a08 1c00 0000 0000 0000 0000 9763 8a53
4 c3c1 8718 9b60 c677 2d4a 648a d3ce a6ba
5 d936 e047 28d0 7f57 93b9 433f eeb8 665c
6 886f 2e17 4381 e91a fd5f 0b01 0000 0000
7 0101 0000 0000 0000 0000 0000 0000 0000
答案 0 :(得分:0)
首先,DataFrame获取一个列表,因此您需要进行适当的列表理解。请尝试以下操作:
with open('blk01530.dat', 'r') as f:
df = pd.DataFrame([l.rstrip() for l in f.read().split()])