0

My csv output is not coming out the way I planned. My code:

first_row = list(ws.rows)[1]
first_row_values = []
first_row_values.append(value1)
first_row_values.append(value2)
first_row_values.append(value3)
first_row_values.extend([cell.value for cell in first_row])
print(first_row_values)
writer = csv.writer(open('output.csv', 'a+'))
writer.writerow([first_row_values])

the output in the file looks like this:

"['value1', 'value2', 'value3', 'valueA', 'valueB', 'valueC', 'valueD', 'valueE', 'valueF', 'valueG', 'valueH', 'valueI', 'valueJ']"

I'm expecting a csv output:

'value1', 'value2', 'value3', 'valueA', 'valueB', 'valueC', 'valueD', 'valueE', 'valueF', 'valueG', 'valueH', 'valueI', 'valueJ'

What am I missing here?

3
  • 3
    remove the [] around first_row_values in the last row. Commented Apr 5, 2018 at 19:27
  • Remove the square brackets in writer.writerow([first_row_values]). Commented Apr 5, 2018 at 19:27
  • first_row_values is already a list, now you made it into a nested list that is the first element of your row, so the whole things gets converted to a string. Commented Apr 5, 2018 at 19:28

2 Answers 2

1

As stated by Mad Physicist and Anton vBR, the set of square brackets, [], is the issue. When you put these brackets around something in python, it will create a list upon execution. So, by putting a list object, first_row_values, within square brackets, you are nesting a list within a new list, as its only element.

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

1 Comment

Thank you to you, Mad Physicist, and Anton vBR. All of you made something clear I didn't understand previously. Thanks again!
1

Just removing the square brackets should give you your result.

  writer.writerow(first_row_values)

1 Comment

sorry Kanchan...I plus'd one for you, but SamBG came first.\

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.