3

我试图使用 python csv 模块将字典写入 csv 文件。

我的字典看起来像这样:

{'PCIP': '192.168.1.4', 'DutIP': '192.168.1.6', 'timestamp': '20120410100340', 'start_time': '0.0', 
 'Transfer bytes': '59457090', 'Port': '5763', 'Lost Datagrams': '10575', 'Percent Lost Datagrams': 
 '20.727', 'PER': 20.727, 'Bandwidth bits': '51684334', 'Throughput': 51.684334, 'end_time': '9.2', 
 'Unknown': '41710', 'Jitter': '0.017', 'ID': '3', 'Total Datagrams': '51020'}

sequence expected当我尝试编写它时,我得到了错误。

有什么办法吗?

def save_result_to_csv_file(self, file, data, header="", access_mode='ab'):
    """
    :param file: local file_name for csv-format logfile
    :type file: str
    :param data: a list or other datatype supported by csv.writerow() 
    :type data: list
    :param header: list containing row names
    :type header: list
    :param access_mode: 'a' append, 'w' write, 'ab' binary append, 'wb' binary write, 'r' read
    :type access_mode: str
    """
    #if file does not exist, start by writing the header row.

    log_file_obj = open(file, 'ab') 
    log_file_writer = csv.writer(log_file_obj)
    if not os.path.isfile(file):
        log_file_writer.writerow(header)
    log_file_writer.writerow(data)
    log_file_obj.flush()
    log_file_obj.close()

     # Labels (Compare to test_case_log_row definition, which matches row_labels)
    interval_data_labels = ["timestamp", "DutIP", "Port", "PCIP", "Unknown", "ID", "start_time", "end_time", "Transfer bytes", "Bandwidth bits"]
    summary_data_labels = interval_data_labels + ["Jitter", "Lost Datagrams", "Total Datagrams", "Percent Lost Datagrams"]
    timestamp_label = ["timestamp"]
    device_info_labels = [ "Device", "Device OS", "Device Bundle"]
    test_results_labels = ["Throughput (MBits/s)", "PER"]
    test_parameters_labels = ["pD.protocol", "pD.test_direction", "pD.execution_time", "pD.send_rate", "pD.packet_size", "pD.transfer_amount"]
    test_data_raw_labels = summary_data_labels
    row_labels = timestamp_label + device_info_labels + test_parameters_labels + test_results_labels + test_data_raw_labels
4

2 回答 2

5

您可以改用DictWriter对象:

import csv

row = {'PCIP': '192.168.1.4', 'DutIP': '192.168.1.6', 'timestamp': '20120410100340', 'start_time': '0.0', 'Transfer bytes': '59457090', 'Port': '5763', 'Lost Datagrams': '10575', 'Percent Lost Datagrams': '20.727', 'PER': 20.727, 'Bandwidth bits': '51684334', 'Throughput': 51.684334, 'end_time': '9.2', 'Unknown': '41710', 'Jitter': '0.017', 'ID': '3', 'Total Datagrams': '51020'}

fp = open('/path/to/file', 'wb')
writer = csv.DictWriter(fp, fieldnames=row.keys())
writer.writerows([row])

注意 row.keys() 中字段名称的顺序。

于 2012-04-10T15:12:14.027 回答
1

这个片段在 2.7 中工作正常

import csv

my_dict =  {'PCIP': '192.168.1.4', 'DutIP': '192.168.1.6', 'timestamp': '20120410100340', 'start_time': '0.0', 
'Transfer bytes': '59457090', 'Port': '5763', 'Lost Datagrams': '10575', 'Percent Lost Datagrams': 
'20.727', 'PER': 20.727, 'Bandwidth bits': '51684334', 'Throughput': 51.684334, 'end_time': '9.2', 
'Unknown': '41710', 'Jitter': '0.017', 'ID': '3', 'Total Datagrams': '51020'}

writer = csv.writer(open("some.csv", "wb"))

writer.writerows(my_dict.viewitems())

如果有必要在标题和列中有键作为应该使用的值

writer.writerow(list(my_dict.viewkeys()))
writer.writerow(list(my_dict.viewvalues()))
于 2012-04-10T14:28:15.080 回答