How to write a list of floats into a CSV file in Python

Question:

I’m trying to get my code to write the following list( a list of 3 floats) in a CSV file in 3 rows.

least_scores=[14.285714285714286, 14.375, 16.5] 

I want it to be saved in rows in the CSV file like below:

14.285714285714286
14.375
16.5

but the program save all the numbers in one row or when I change the code I get the error that float is not iterable. I have tried many things and checked a lot of similar questions here and there, but I can not find the solution to my problem.

the following codes are the things that I have tried so far:

import csv
from statistics import mean
with open("E:\Chapter5input_file_name.csv") as inputi:
    data_list=[]
    score_list=[]
    mean_list=[]
    reader=csv.reader(inputi)
    for rows in reader:
        data_list.append(rows)
    #print(len(data_list))
    for i in range(0,len(data_list)):
        score_list.append(data_list[i][1:])
    #print(score_list)
    new_list=[
        [float(x) for x in nested_lists]
        for nested_lists in score_list
    ]
    #print(new_list)
    for items in new_list:
        mean_list.append(mean(items))
    #print(mean_list)
    least_scores=sorted(mean_list)
    least_scores=least_scores[0:3]
    print(least_scores)
    with open("E:\Chapter5output_file_name.csv",'w',newline='') as outi:
        writer=csv.writer(outi)
        writer.writerow(least_scores)

with the above code the list items will all be saved in a single row.

so I tries writer.writerows instead of writer.writerow but I got the error "iterable expected, not float"

the I tried the following code:

with open("E:\Chapter5output_file_name.csv",'w',newline='') as outi:
        writer=csv.writer(outi)
        for nums in least_scores:
            writer.writerows(nums)

and got the error "’float’ object is not iterable"
Could you please help me solve this issue please?

Asked By: Annahita

||

Answers:

Well done on including a shorter bit of code, that helps with debugging.
Can you share the full stack next time as well please?

I think in this case, the issue is that least_scores is MEANT to be a list of floats, but you just have a float there.

Answered By: Aron Atilla Hegedus

writerow() is looking for an iterable, the value in nums can be passed within a list to satisfy that:

with open("file_name.csv", 'w', newline='') as outi:
    writer = csv.writer(outi)
    for nums in least_scores:
        writer.writerow([nums])
Answered By: Jorge Gx
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.