读取Json文件以提取数据并生成CSV文件

时间:2019-03-28 16:23:22

标签: python python-2.7

我不确定,但是有人认为这与读取文件的循环有关 如果有人可以看看我的代码并指出错误,那将是很大的

我得到的错误是KeyError: 'MBWritten'

我的代码是:

for file_name in file_name_list:
    with open(file_name) as data_file:
        data = json.load(data_file)
        symmetrixID= data['symmetrixID']
        pgname= data['pgname']
        for row in data['perf_data']:
            MBWritten = row['MBWritten']
            timestamp = row['timestamp']
            Writes = row['Writes']
            AvgIOSize = row['AvgIOSize']
            Reads = row['Reads']
            MBRead = row['MBRead']
            PercentBusy = row['PercentBusy']
            IOs = row['IOs']
            MBs = row['MBs']
        for timestamp in [timestamp]:
            EXEC_TIME = epoch2human(timestamp)
            joined = ",".join([str(c) for c in [symmetrixID, pgname, MBWritten, MBRead,
                                                Reads, Writes, MBs, AvgIOSize,
                                                PercentBusy, IOs, EXEC_TIME]])
            print(joined)

2 个答案:

答案 0 :(得分:0)

错误告诉您“ MBWritten”在当前行中不存在。

您可以使用dict.get()方法来避免此错误。例如:

row.get('MBWritten')

如果找不到密钥,它将返回None。如果您想设置默认值(如果找不到该键),则只需将其添加为第二个参数即可。例如:

row.get('MBWritten', 0)

答案 1 :(得分:0)

该错误表示该行没有名为“ MBWritten”的字段

如果不了解您data_file中的实际数据,我们将无法帮助调试。

不过,错误的要点是您要从该file_name中将数据作为json加载,然后遍历“ perf_data”键的每个字段。该数据中的某处没有“ MBWritten”字段,您遇到了关键错误。

如果您的数据看起来像这样并且字段缺少MBWritted,则会出现此错误

{
  'perf_data': [
                 {'MBWritten': 7, 'timestamp': 1234, ...},
                 {'timestamp': 8837, ...}
               ]
}