Write A List To Csv File Without Looping In Python
Solution 1:
There is a writerows
method which will add all the rows in an 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). 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. 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
.
Solution 2:
Solution 3:
These are all tuples of strings? Only 40,000 of them? Have you tried this?
withopen('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.
Post a Comment for "Write A List To Csv File Without Looping In Python"