简体   繁体   English

将列表写为tsv文件中的列

[英]Write lists as columns in tsv file

I have three lists which I wish to store in a tsv file as follows: 我希望将三个列表存储在tsv文件中,如下所示:

 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: 以下代码使用csv writer方法存储它:

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. 但是,由于tsv和csv之间的格式差异,此方法在以后的处理中会导致一些错误SyntaxError: Got u'"\\t1.0' 。因此,有另一种方法可以不使用csv SyntaxError: Got u'"\\t1.0'我正在使用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. 如果col数据中还包含一个'\\ t',则必须搜索每个列表项并将其用引号引起来...可以在必要时进行更新。

If there are unicode characters, you can define that in the writing operation when you open the file. 如果存在Unicode字符,则可以在打开文件时在写入操作中进行定义。

Hope that helps 希望能有所帮助

csv.writer needs to be passed a open file object csv.writer需要传递一个打开文件对象

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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