我正在尝试从我的锅炉中读取一些日志文件,但它们的格式很差。
当我尝试用
读取文件时import pandas
print(pandas.read_csv('./data/CM120102.CSV', delimiter=';'))
我得到了
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 49: invalid start byte
由于某种原因,csv标头以空字节结束。
https://gist.github.com/Ession/6e5bf67392276048c7bd
http://mathiasjost.com/CM120102.CSV< ==这个应该可以工作(或者说不工作)
有没有办法用pandas读取这些文件而不先修复它们?
答案 0 :(得分:3)
我会把它读成一个字符串。然后在python中进行一些修改,然后将其传递给pandas.read_csv。示例代码如下。
# get the data as a python string
with open ("CM120102.CSV", "r") as myfile:
data=myfile.read()
# munge in python - get rid of the garbage in the input (lots of xff bytes)
import re
data = re.sub(r'[^a-zA-Z0-9_\.;:\n]', '', data) # get rid of the rubbish
data = data + '\n' # the very last one is missing?
data = re.sub(r';\n', r'\n', data) # last ; separator on line is problematic
# now let's suck into a pandas DataFrame
from StringIO import StringIO
import pandas as pd
df = pd.read_csv(StringIO(data), index_col=None, header=0,
skipinitialspace=True, sep=';', parse_dates=True)