python list to csv file with each item in new line

后端 未结 5 545
无人及你
无人及你 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:59

    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.

提交回复
热议问题