简体   繁体   中英

Write lists as columns in tsv file

I have three lists which I wish to store in a tsv file as follows:

 1 a yes
 2 b no 
 3 c yes

The lists:

list1 = [u'1', u'2', u'3']
list2 = [u'a', u'b', u'c']
list3 = [u'yes', u'no', u'yes']

The following code stores it using a csv writer method:

rowlists = zip(list1, list2, list3)
writer = csv.writer(outfile, delimiter='\t')
for row in rowlists:
     writer.writerow(row)

However, this method is causing some errors in later processing due to to format differences I guess between tsv and csv SyntaxError: Got u'"\\t1.0' . So, is there another way to do it without the use of the csv writer? I'm using python 2.7.

Any help will be truly appreciated. Thanks,

If you did not want to use a writer, you could do this manually. But note that managing quotes for columns that contain the delimiter would be a little hard:

Simplest method:

numItems = len(l1)
outputStr = ''

for i in range(0,numItems): 
  outputStr += l1[i] + "\t" + l2[i] + "\t" + l3[i] + "\n"


with open('output.tsv', "w") as outputter:
  outputter.write(outputStr)

If col data also contains a '\\t', you'll have to search each list item and wrap it in quotes...can update if necessary.

If there are unicode characters, you can define that in the writing operation when you open the file.

Hope that helps

csv.writer needs to be passed a open file object

with open(outfile, 'w+') as f:
    writer = csv.writer(f, delimiter='\t')
    for row in rowlists:
        writer.writerow(row)

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