Use csv
module by import csv
also take a note you might need either writerow()
or writerows()
.
What's the difference you may ask?
writerow takes an iterable of cells to write:
writerow([1,2,2])
->
1,2,2
writerows takes an iterable of iterables of cells to write:
writerows([[1,2,3],
[4,5,6],
[6,7,8]])
->
1,2,3
4,5,6
6,7,8
Which can be ofcourse be given as a variable. Like
a = [[1,2,3],[4,5,6],[6,7,8]]
writerows(a)
Conclusion writerow takes 1-dimensional data (one row), and writerows takes 2-dimensional data (multiple rows).
Program for you:
import csv
a = [[1,2,3,4],[5,6,7,8]]
with open("new_file.csv","w+") as my_csv:
csvWriter = csv.writer(my_csv,delimiter=',')
csvWriter.writerows(a)
Note open()
takes two arguments here the file to be written and the mode.
What is a mode you may ask?
It specifies how the file should be opened. In my case w+
means open file my_file.csv
if it exists if it doesn't then fine create a new one and write.
There are several modes choose one. Note: w+
overwrites everytime you use it. That is old data in file will be overwritten so if you want to just append use a
. Take a look at this for more details on modes.File modes