简体   繁体   English

Python,转置列表并写入CSV文件

[英]Python, transposing a list and writing to a CSV file

I need to write into a csv file using python and each iterator item should start in a new line. 我需要使用python写入csv文件,每个迭代器项应该以新行开头。 So delimiter I am using is "\\n". 所以我使用的分隔符是“\\ n”。 After each list has been written,next list should write from next cell. 写完每个列表后,下一个列表应该从下一个单元格写入。 like below: 如下:

 lol = [[1,2,3],[4,5,6]]

The csv will be like: csv将如下:

1 4
2 5
3 6

What I have tried: 我尝试过的:

file = open("test.csv", "wb")
fileWriter = csv.writer(file , delimiter='\n',quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamWriter.writerow([1,2,3])
spamWriter = csv.writer(file , delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamWriter.writerow([4,5,6])
file.close()

Which results like below: 结果如下:

 1
 2
 3
 4 5 6

Using csv module how can I get output like below: 使用csv模块如何获得如下输出:

 1 4 
 2 5
 3 6

here space means comma in a csv file. 这里的空格表示csv文件中的逗号。

Thanks. 谢谢。

Without using zip, you could do this: 不使用zip,你可以这样做:

import csv

lol = [[1,2,3],[4,5,6],[7,8,9]]
item_length = len(lol[0])

with open('test.csv', 'wb') as test_file:
  file_writer = csv.writer(test_file)
  for i in range(item_length):
    file_writer.writerow([x[i] for x in lol])

This will output into test.csv: 这将输出到test.csv:

1,4,7
2,5,8
3,6,9

first transpose your input by using zip() 首先使用zip()转置输入

>>> zip(*lol)
[(1, 4), (2, 5), (3, 6)]

and after that just pass it to csw.writer eg 然后将其传递给csw.writer例如

with open("test.csv", "wb") as f:
    fileWriter = csv.writer(f, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for row in zip(*lol):
        fileWriter.writerow(row)

... which results to: ......结果是:

$ cat test.csv 
1,4
2,5
3,6

If you are using Python3 you need to open files in text format "wt", more over csv has writerows that can be used to write everything at once. 如果您使用的是Python3,则需要以文本格式“wt”打开文件,而csvwriterows可以用于一次写入所有内容的编写器。 here is an example: 这是一个例子:

data=[("test", "value1", "value2"), ("test2", "value3", "value4")]
with open('my.csv','wt') as out:
   csv_out=csv.writer(out)
   csv_out.writerows(data)

I've just noticed that the question ask how to transform the list, that is a separate step and here is how I would do it: 我刚刚注意到问题是如何转换列表,这是一个单独的步骤,这就是我将如何做到这一点:

lol = [[1,2,3],[4,5,6]]
data = zip(lol[0],lol[1])

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

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