I am trying to write a function that takes in a list of strings and writes each String in the list as a separate row in a csv file, but I am not getting any output. Could yo
You can change the code as follows:
import sys
import os
import csv
listOfLines= [['name@domain.com', 'name@domain.com', 'name@domain.com', 'name@domain.com', 'name@domain.com', 'name@domain.com']]
def write_to_csv(list_of_emails):
with open('emails.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter = ',')
writer.writerows(list_of_emails)
write_to_csv(listOfLines)
The function writer.writerows()
takes a list of lists, in our case
[['name@domain.com', 'name@domain.com', 'name@domain.com', 'name@domain.com', 'name@domain.com', 'name@domain.com']]
,
where every sub-list inside the original list is treated as a single line of the CSV file.
You also should not use reserved keywords like list
for variable names. list
,dict
are functions used to create Lists and Dictionaries respectively. May be in your code it did not throw any error, but for scripts that are larger than the current piece of code in question, the interpreter throws errors for the same and such errors become harder to debug