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 に答える