i have taken 6 different input from users and have stored them in 6 different lists. Now my question is how can I add those 6 lists in 6 different columns in csv file without using pandas? I would be forever grateful for your help?
Asked
Active
Viewed 777 times
3 Answers
0
As done here: Write dictionary of lists to a CSV file
I would suggest saving all the lists into a dictionary with the keys being the headings wanted for the csv and then save it to csv as done in the answer withing that question.

Kwsswart
- 529
- 1
- 7
- 20
0
d = {"key1": [1,2,3], "key2": [4,5,6], "key3": [7,8,9]}
with open("test.csv", "wb") as outfile:
writer = csv.writer(outfile)
writer.writerow(d.keys())
writer.writerows(zip(*d.values()))

taha yab
- 41
- 2
- 6
0
I don't normally give an answer unless the OP has already made an attempt at a solution. But since there have been a couple of answers, I will offer mine:
First, according to the the documentation, the file should be opened in a very specific way, i.e. as a text file and specifying newline=''
) to ensure that each line in the output is terminated with the \r\n
as required by the CSV specification.
import csv
column_headers = [
'header1', 'header2', 'header3', 'hedader4', 'header5', 'header6'
]
column1 = ['a1', 'a2']
column2 = ['b1', 'b2']
column3 = ['c1', 'c2']
column4 = ['d1', 'd2']
column5 = ['e1', 'e2']
column6 = ['f1', 'f2']
with open('test.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(column_headers) # if you want column headers
writer.writerows(zip(column1, column2, column3, column4, column5, column6))

Booboo
- 38,656
- 3
- 37
- 60
-
Thankyou so much your code is very precise and it worked. But I have one more question. what if we want to skip some column. For example I am doing research on Covid Vaccine and it asks the user whether or not you got the vaccine. If the user says no then I do not need to store rest of information in front of this user name nor will program ask further question. But on the file answers of next user are stored in front of previous user name. How to avoid that? Eagerly waiting for your kind response – Adnan Kayani Mar 28 '21 at 18:49
-
... and some code! You can then add a comment to your new post with @Booboo at the beginning so I am alerted to the new question. – Booboo Mar 28 '21 at 19:09
-
Thank you so much for your cooperation and I am really sorry for not posting my question in appropriate formate, will take care next time @Booboo – Adnan Kayani Mar 29 '21 at 06:24