Home > Mobile >  writing a whole list into one row in csv python
writing a whole list into one row in csv python

Time:05-17

I have a list and a variable

myList = ['a', 'b', 'c', 'd']
myVariable = 10

and I would like to write this list and the variable to a CSV file using Python and it should be written like this (but with tab between adjacent values and without ","):

10 a b c d

and not like this:

10
a
b
c
d

So far I have:

myList = ['a', 'b', 'c', 'd']
file = open("CSVfile"   '.csv','w', newline='', encoding='utf-8')
writer = csv.writer(file)
writer.writerow(myVariable)
writer.writerow(myList)

CodePudding user response:

First off, try not to name your variables the same as builtin types (list). This can break lots of stuff. Edit: nvm I saw you edited your post.

You can just merge the list and variable into a string and then write that. You don't even need the csv writer.

myList = [a,b,c,d]
with open("CSVfile"   '.csv','w', encoding='utf-8') as f:
    line = '\t'.join([myVariable]   myList)
    f.write(line   '\n')

CodePudding user response:

If you want to use the csv module as your question suggests (docs here), you can do it this way:

import csv
myList = ['a', 'b', 'c', 'd']
myVariable = 10
with open('CSVfile.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file, delimiter='\t')
    writer.writerow([myVariable]   myList)

Note that delimiter is specified as '\t' (tab) in the call to csv.writer(), and we append the variable and the list to create a new list which is used as an argument to writerow().

  • Related