Writing data to a text file in Python

Question:

I am trying to write mean,var,std to a .txt file but I am getting an error.

import csv
mean = 50.00001075309713
var = 4.120598729047652
std = 2.0299257939756448

with open('Radius.txt', 'w+') as f: 
    writer = csv.writer(f)
    print("Mean =",mean)
    print("var =",var)
    print("std =",std)
    writer.writerow(mean)
    writer.writerow(var)
    writer.writerow(std)

The error is

in <module>
    writer.writerow(mean)

Error: iterable expected, not float

The expected output is

mean = 50.00001075309713
var = 4.120598729047652
std = 2.0299257939756448
Asked By: user19862793

||

Answers:

Change:

writer.writerow(mean)
writer.writerow(var)
writer.writerow(std)

to:

writer.writerow((mean, var, std))

The requirement for an iterable means whatever you pass to writerow must be something which can be looped through. The fix here is to put your values into a tuple, the inner bracketed values. It works because tuples can be looped through.

To write the values as a single line with variable prefixes (OP’s comment) use:

writer.writerow((f'{mean = }  {var = }  {std = }', ))
Answered By: Crapicus

Based on the clarification from the comments a way without using csv but just a txt file:

mean = 50.00001075309713
var = 4.120598729047652
std = 2.0299257939756448

with open('Radius.txt', 'w+') as f: 
    f.write(f"mean = {str(mean)}n")
    f.write(f"var = {str(var)}n")
    f.write(f"std = {str(std)}n")
Answered By: MagnusO_O
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.