简体   繁体   中英

writing a whole list into one row in csv python

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)

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')

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM