如何将多个值写入文本文件的一行中

3

我有一个数字和字符串,分别为a、x、y和z。我想将它们写入一个文本文件中,并使所有的值都在一行上。例如,我希望文本文件如下:

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

每次循环完成后,都要将该时间点的所有变量写入新的文本行。请问如何实现此功能?


2
你能给我们提供那段代码以及你尝试过的吗? - utdemir
2个回答

10
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)) 

或者,如果您想收集所有的值然后一次性写入它们

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)

3

一句笑话:

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

如果您愿意,可以使用with将文件操作分离。

您必须提供strings = 'axyz'strings = ['some','other','strings','you','may','have']

如果您的数字不总是1, 2, 3, 4,请用您的列表替换range(1,len(strings)+1)...


为了好玩而已 ✊。 - Zack Plauché

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接