简体   繁体   English

将列表写入csv文件而不在python中循环

[英]Write a list to csv file without looping in python

I have a list of list of lists that I need to write to a csv file. 我有一个列表列表,我需要写入csv文件。

mylist = [['Siddharth','Bangalore','blah@gmail.com'],  
        ['Rahul','Bangalore','blah2@gmail.com'],.....and so on]  

This list is usually some 20,000 to 40,000 long. 这个列表通常是20,000到40,000长。
So, right now, the only way to write them to a csv file is to iterate over the list and write: 所以,现在,将它们写入csv文件的唯一方法是迭代列表并写入:

fileObj = open("/home/siddharth/sample.csv", "wb")
csv_file = csv.writer(fileObj)  
for item in mylist:  
    csv_file.writerow(item)  

So, I just to wanted to know, is there a way to write such a list of lists to csv, without iterating over each item in the list, eg. 所以,我只是想知道,有没有办法将这样的列表列表写入csv,而不是迭代列表中的每个项目,例如。 like using StringIO etc. 比如使用StringIO
Or, can anyone give some tip/hint, so that I can create my own implementation. 或者,任何人都可以提供一些提示/提示,以便我可以创建自己的实现。

There is a writerows method which will add all the rows in an iterable: 有一个writerows方法,它将在iterable中添加所有行:

csv_file.writerows(the_list)

Whatever you do, there will always be a loop somewhere (either in your code or in the Python library implementation). 无论你做什么,总会有一个循环(在你的代码或Python库实现中)。 There is no way around it as you need to look at each item in the list so that you can write them to the file. 没有办法绕过它,因为您需要查看列表中的每个项目,以便您可以将它们写入文件。

In case you're worried about the performance of writing each line to the file separately: Python uses buffered I/O by default, so even if you write the list items one by one in a loop, they won't necessarily be written like that to the file. 如果您担心单独将每行写入文件的性能:默认情况下Python使用缓冲的I / O,因此即使您在循环中逐个编写列表项,它们也不一定会像到文件。 They will be written in chunks whenever the buffer fills up, which will have better performance. 每当缓冲区填满时,它们将以块的形式写入,这将具有更好的性能。 If needed, you can explicitly control the buffer size by using the buffering parameter of open . 如果需要,可以使用openbuffering参数显式控制缓冲区大小。

Easy: 简单:

csv_file.writerows(mylist)

(Note the s in writerows() ) (注意在writerows()s

These are all tuples of strings? 这些都是字符串的元组? Only 40,000 of them? 只有40,000个? Have you tried this? 你试过这个吗?

with open('outputfile.csv','w') as csv_file:
    csv_file.write('\n'.join(map(','.join, my_list)+'\n'))

You are still iterating over the list, but doing so using map , which is implemented in Python's C library. 仍在迭代列表,但使用map ,这是在Python的C库中实现的。

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

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