0

Suppose now I have a date and a list of groups(group A, group B, etc.) and would like to write all of them in one row in a CSV file. I have tried the following code but there are several problems.

import csv
with open('test.csv', 'w') as file:
output = csv.writer(file)
output.writerow('Date')  
for i in range(0,len(c)): 
 output.writerow([lst[i]]) #lst is the list containing the group number

The output here is

D a t e

Group A

Group B

Group C

The first issue is that each character in Date is treated separately, each of them appears in separate columns.

The second issue is that there is a new line between each row which is not desired.

Lastly, instead of writing them in rows, I want them to be in one row with multple columns. The ideal output should be as follows

Date Group A Group B Group C

1 Answer 1

1

You need to combine all the elements you want included in the row into a single list:

import csv
with open('test.csv', 'w') as file:
  output = csv.writer(file)
  out = ['Date']
  for i in range(0,len(c)): 
   out.append(lst[i])
  output.writerow(out)  
Sign up to request clarification or add additional context in comments.

1 Comment

out = ["Date"] + c (if c is a list) or out = ["Date"] + list(c) (if c is a tuple etc).

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.