0

Why is my CSV write function not working? This seems to be a very simple code but the CSV writerow is asking for an iterable. I just need to write the 1,2,3 in a column.

import csv

data = [1,2,3]

output = 'output.csv'

with open(output,'w') as f:
    writer = csv.writer(f)
    for item in data:
        writer.writerow(item)
6
  • Have you seen this question? I think that writerow expects a list. stackoverflow.com/a/39282731/92953 Commented Jul 1, 2020 at 2:41
  • 1
    A row must be an iterable of strings or numbers for Writer objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str() first) for DictWriter objects. docs.python.org/3/library/csv.html Commented Jul 1, 2020 at 2:42
  • try changing to, writer.writerow([item]) Commented Jul 1, 2020 at 2:58
  • Not to be overly picky, but if there is literally only one value on each line, why is CSV getting involved? For consistent newline format? Because you didn't pass newline='' to open, so you won't be getting that anyway. Commented Jul 1, 2020 at 3:03
  • What can I use if not CSV? Are you implying I use txt instead? Commented Jul 1, 2020 at 3:56

2 Answers 2

2

You are passing an integer but a list is expected.

import csv

data = [[1],[2],[3]]

output = 'output.csv'

with open(output,'w') as f:
    writer = csv.writer(f)
    for item in data:
        writer.writerow(item)
Sign up to request clarification or add additional context in comments.

Comments

2

We need to provide a list to the CSV writer writerow function, in which there are values for 1 complete row.

e.g

import csv

data = [1,2,3]

output = 'output.csv'

with open(output,'w') as f:
    writer = csv.writer(f)
    writer.writerow(data) # as data includes only 1 row. For multiple rows write every row with a loop

Comments

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.