+3 votes
in Programming Languages by (14.6k points)

I want to write records to a CSV file using python, but the following code gives error - "_csv.Error: iterable expected, not NoneType". What is the problem in this code?

    ofile = 'XGB_outputs/persons_all_covars.csv'
    with open(ofile, 'w') as mpf:
        csvwriter = csv.writer(mpf)
        line = ['Person_id', 'True class', 'Class1 prob', 'Predicted class'].extend([str(conditions[i]) for i in idx])
        csvwriter.writerow(line)
 

1 Answer

0 votes
by (25.6k points)

As the error message says, your variable 'line' is None. It does not have any data.

You are using the extend() function wrongly which makes the variable 'line' None. You cannot assign like this when you are using extend():

line = ['Person_id', 'True class', 'Class1 prob', 'Predicted class'].extend([str(conditions[i]) for i in idx])

 Modify your code as highlighted below to fix the error.

ofile = 'XGB_outputs/persons_all_covars.csv'
with open(ofile, 'w') as mpf:
    csvwriter = csv.writer(mpf)
    line = ['Person_id', 'True class', 'Class1 prob', 'Predicted class']
    line.extend([str(conditions[i]) for i in idx])

    print(line)
    csvwriter.writerow(line)

...