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

Write every nth line from list to new row in csv file

I have a list that contains numbers like this:

[20.5, 21.7, 23.0, 23.6, 24.0, 24.7]

and i want to write the list to a csv file that should look like this:

20.5, 21.7
23.0, 23.6
24.0, 24.7

so every second line in my list should be written to the next row in the csv file.

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

right now my script just looks like this:

import csv

with open('result.csv','w') as f:
    for line in my_list:
        f.write("%s\n" % line)

how can i write only every nth line as a new line and every nth line as new row?

>Solution :

If you don’t need the space after the comma:

import csv

data = [20.5, 21.7, 23.0, 23.6, 24.0, 24.7]

with open('result.csv','w') as file:
    csv.writer(file).writerows(data[i:i + 2] for i in range(0, len(data), 2))

Otherwise:

with open('result.csv','w') as file:
    file.writelines(
        ", ".join(map(str, data[i:i + 2])) + "\n" for i in range(0, len(data), 2)
    )
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