Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write multiple values into one line in a text file

Tags:

python

I have a number and strings, a, x, y, and z. I want to write a them to a text file with all of those values in one line. For example, I want the text file to say:

a1 x1 y1 z1
a2 x2 y2 z2
a3 x3 y3 z3
a4 x4 y4 z4

There's a loop and each time the loop completes a cycle, I want to write all of the variables at the given time, into a new line of text. How do I do this?

like image 660
Naveen C. Avatar asked Jan 25 '26 06:01

Naveen C.


1 Answers

with open('output', 'w') as fout:
    while True:
        a, x, y, z = calculate_a(), calculate_x(), calculate_y(), calculate_z()
        fout.write('{} {} {} {}\n'.format(a, x, y, z)) 

or, if you want to collect all the values and then write them all at once

with open('output', 'w') as fp:
    lines = []
    while True:
        a, x, y, z = calculate_a(), calculate_x(), calculate_y(), calculate_z()
        lines.append('{} {} {} {}\n'.format(a, x, y, z))
    fp.writelines(lines)
like image 163
BenTrofatter Avatar answered Jan 27 '26 23:01

BenTrofatter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!