0

I have a list of unicode string that I want to write to a cvs file.

with open(archive_dir_today + 'myfile.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(list_diff_1)

this work fine, except that it writes every character in a separate cell. For example the first entry in the list is "1000F034E2" I end up with a row in the csv file that looks like this:

1,0,0,0,F,0,3,4,E,2

what is causing that problem?

1 Answer 1

1

You are using the wrong method; writer.writerows() expects multiple rows, but you only have one row. Use writer.writerow() (singular, no s) instead.

What happens is that because writerows() expects a list of rows, it treats each column in your single row as a list; the list of a unicode string is its individual characters:

>>> list(u'1000F034E2')
[u'1', u'0', u'0', u'0', u'F', u'0', u'3', u'4', u'E', u'2']

That's the row of columns being written out in that case.

If you wanted each item in the list as separate rows, then wrap them in list objects:

writer.writerows([column] for column in list_diff_1)
Sign up to request clarification or add additional context in comments.

1 Comment

I want each item in the list on a separate row. Not all in one row.

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.