+2 votes
in Programming Languages by (9k points)

I am creating a CSV file using csv module of python, but am getting TypeError: a bytes-like object is required, not 'str' error with the following code. How can I solve it?

    fieldnames = domain_list + ['Ancestor', 'AUC', 'MCC', 'Accuracy']
    csvfile = open (wv.full_fact_matrix_file, 'wb')
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

    datarow = {}
    for k,v in performance_data_dict.items():
        for field in fieldnames:    # initialize dictionary
            if (field in k):
                datarow[field] = '1'
            else:
                datarow[field] = '0'
        if (anc == 'Y'):
            datarow['Ancestor'] = '1'
        else:
            datarow['Ancestor'] = '0'

        datarow['AUC'] = v[0]
        datarow['MCC'] = v[1]
        datarow['Accuracy'] = v[2]
        writer.writerow(datarow)
 

1 Answer

+1 vote
by (11.3k points)

If you are using python 2, the above code should not give error. If you are using python 3, make the following changes in your code and then it should work.

Change

csvfile = open (wv.full_fact_matrix_file, 'wb')

to

csvfile = open (wv.full_fact_matrix_file, 'w')

...