开发者

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

I have a number and strings, a, x, y, and z. I wa开发者_如何学Gont 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?


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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜