python list to csv file with each item in new line

后端 未结 5 648
无人及你
无人及你 2021-01-19 02:10

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

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-19 02:49

    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

提交回复
热议问题