简体   繁体   中英

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.

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?

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)
    )

This is a simple way without using any libraries.

import csv
my_list = [20.5, 21.7, 23.0, 23.6, 24.0, 24.7]
nth_line = 2 #--> You can give other values too.
with open('result.csv','w') as f:
    for line in range(len(my_list)):
        f.write(str(my_list[line]))
        if (line+1) % nth_line == 0:
            f.write('\n')
        else:
            f.write(', ')

By re-shaping the list, then writing all at once:

import csv

data = [20.5, 21.7, 23.0, 23.6, 24.0, 24.7]
data = [data[x:x+2] for x in range(0, len(data), 2)]

with open("results.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerows(data)

This will word for odd lengths as well:

# len = 7
data = [20.5, 21.7, 23.0, 23.6, 24.0, 24.7, 0]

results.csv

20.5,21.7
23.0,23.6
24.0,24.7
0

I've come up with this solution that works in all cases:

from math import *

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

values_per_line = 2

with open('result.csv','w') as f:
    i = 0
    number_of_lines = ceil(len(my_list)/values_per_line)
    for line in range(number_of_lines):
        for value in range(values_per_line):
            if i < len(my_list)-1:
                if value == (values_per_line - 1):
                    f.write("%s" % my_list[i])
                else:
                    f.write("%s, " % my_list[i])
            elif i == len(my_list)-1:
                f.write("%s" % my_list[i])
            i = i + 1

        if line != number_of_lines-1:
            f.write("\n")

You can change the values_per_line to whatever you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM