3

I an attempting to use the python csv module to write a dictionary to a csv file.

My dictionary looks something like this:

{'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'}

I get the error sequence expected when I attempt to write it.

Is there any way to do so?

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
  • 1
    It is helpful to post the code that you've tried when asking a question like this. Commented Apr 10, 2012 at 14:13
  • As you're writing out a dictionary, have you specified the field names as header fields in the constructor? Only in that case can a dictionary be written out directly by csv.writerow() - if you don't set up header names (i.e., order of field names), writerow() will refuse to write dictionaries. Commented Apr 10, 2012 at 14:14
  • Yes, post the code, you have got the function arguments in the wrong order, I bet. Commented Apr 10, 2012 at 14:15
  • 1
    We mean you have to post the code where you are writing to the csv. My guess is you aren't using csv.DictWriter Commented Apr 10, 2012 at 14:18

2 Answers 2

5

You could use the DictWriter object instead:

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])

Beware of the order of field names in row.keys().

Sign up to request clarification or add additional context in comments.

Comments

1

This snippet works ok in 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())

If it is necessary to have keys in headers and columns to be the values one should use

writer.writerow(list(my_dict.viewkeys()))
writer.writerow(list(my_dict.viewvalues()))

6 Comments

probably, you was using writerow() instead of writerows() - that caused 'sequence expected' error.
What does the csv file look like?
What I would like is the headers to be the keys and the columns to be the values. is that possible?
The headers appear correctly, but the fields appear like this: ('PCIP', '192.168.1.4') ('DutIP', '192.168.1.6') ('timestamp', '20120410113158')
This won't work! Since in Python dicts have no order each time the OP calls save_result_to_csv_file, data might get written in a different order. As @Greg Leclercq's answer, and my comment on the question. Have a look at csv.DictWriter
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.