使用 pandas read_csv 时跳过 0xff 字节

Skipping 0xff byte when using pandas read_csv

我正在尝试从我的锅炉中读取一些日志文件,但它们的格式很糟糕。

当我尝试使用

读取文件时
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 header 以空字节结尾。

https://gist.github.com/Ession/6e5bf67392276048c7bd

http://mathiasjost.com/CM120102.CSV <== 这个应该有效(或者更确切地说无效)

有没有什么方法可以使用 pandas 读取这些文件而不先修复它们?

我会把它读成一个字符串。然后在 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)