Naveen C.
Naveen C.

Reputation: 3345

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

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?

Upvotes: 3

Views: 14921

Answers (2)

BenTrofatter
BenTrofatter

Reputation: 2158

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)

Upvotes: 10

JBernardo
JBernardo

Reputation: 33387

One-liner for the lulz:

open('file','w').writelines(' '.join(j+str(i) for j in strings) + '\n' for i in range(1,len(strings)+1))

You can separate the file operation with with if you want. You must provide strings = 'axyz' or strings = ['some', 'other', 'strings', 'you', 'may', 'have']

And, if your numbers aren't always 1, 2, 3, 4, replace range(1,len(strings)+1) with your list...

Upvotes: 3

Related Questions