Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python | How to append data to csv file with new line

I have this dataset here:

import csv

numbers = [111, 222, 333, 444]

And I want to be able to output the contents to a csv file like so with no header:

111
222
333
444

I’ve tried this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

with open('numbers.csv', 'a') as nums:
    writer = csv.writer(nums, lineterminator='\n')

    writer.writerow(numbers)

Output:

111,222,333,444

I know it’s because I’m using writerow(), but I have no clue how to write to the csv file without making it so. I’ve tried nums.write() but again, no clue how to space new lines

>Solution :

writer.writerow actually takes a list as an argument and interpretes it like a CSV row. So I suppose you are trying to create a new row for each element in your list.
This is a way to do that:

import csv

numbers = [111, 222, 333, 444]

with open('numbers.csv', 'a') as nums:
    writer = csv.writer(nums, lineterminator='\n')

    for i in numbers:                     # iterate through your list
        writer.writerow([i])              # write a row containing each element
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading