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 x
Solution 1:
withopen('output', 'w') as fout:
whileTrue:
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)
Solution 2:
One-liner for the lulz:
open('file','w').writelines(' '.join(j+str(i) for j in strings) + '\n'for i inrange(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...
Post a Comment for "How To Write Multiple Values Into One Line In A Text File"