Reputation: 525
I am trying to write a program that will write a list of info in a text file. Here's an example of what I have so far
f.open('blah.txt','w')
x = input('put something here')
y = input('put something here')
z = input('put something here')
info = [x,y,z]
a = info[0]
b = info[1]
c = info[2]
f.write(a)
f.write(b)
f.write(c)
f.close()
However i need it to write it in a list-like format so that if I input
x = 1 y = 2 z = 3
then the file will read
1,2,3
and so that the next time I input info it will write it in a newline like
1,2,3
4,5,6
How can I fix this?
Upvotes: 0
Views: 1912
Reputation: 8040
Use a complete, ready to use, serialization format. For example:
import json
x = ['a', 'b', 'c']
with open('/tmp/1', 'w') as f:
json.dump(x, f)
File contents:
["a", "b", "c"]
Upvotes: 1
Reputation: 5755
Try this:
f.open('blah.txt','a') # append mode, if you want to re-write to the same file
x = input('put something here')
y = input('put something here')
z = input('put something here')
f.write('%d,%d,%d\n' %(x,y,z))
f.close()
Upvotes: 1
Reputation: 65861
Format a string and write it:
s = ','.join(info)
f.write(s + '\n')
Upvotes: 2