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
Why don't you try doing it with pandas instead. It's super easy. :)
lst = ['name@domain.com', 'name@domain.com', 'name@domain.com', 'name@domain.com', 'name@domain.com', 'name@domain.com']
First, import package
import pandas
Then, create dataframe
df = pandas.DataFrame(data={"email": lst})
Then, export to csv :)
df.to_csv("./mycsv.csv", sep=',',index=False)
Done :) let me know if this one works for you!
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
You can use delimiter='\n'
with csv.writer.writerow
(notice, not writerows
). In addition, newline=''
is not required as an argument to open
.
import sys
import os
import csv
L = ['name1@domain.com', 'name2@domain.com', 'name3@domain.com']
def write_to_csv(list_of_emails):
with open('emails.csv', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter='\n')
writer.writerow(list_of_emails)
write_to_csv(L)
If your just writing each string on a seperate line, you can just keep it simple and just write each item with a \n
:
lst= ['name1@domain.com', 'name2@domain.com', 'name3@domain.com']
def write_to_csv(list_of_emails):
with open('emails.csv', 'w') as csvfile:
for domain in list_of_emails:
csvfile.write(domain + '\n')
write_to_csv(lst)
Which Outputs:
name1@domain.com
name2@domain.com
name3@domain.com
You also shouldn't use list
as a variable name, since it shadows the builtin function list
.
You need to use writerow
Ex:
import sys
import os
import csv
l= ['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 = '\n')
writer.writerow(list_of_emails)
write_to_csv(l)