2013-06-21 88 views
0

我想写一个程序,它将在文本文件中写入信息列表。下面是我到目前为止Python以列表格式写入文件

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

但是我需要它,把它写在一个类似列表的形式的例这样,如果我输入

x = 1 y = 2 z = 3 

那么该文件将读取

1,2,3 

这样下一次我输入信息就会把它写成新行像

1,2,3 
4,5,6 

我该如何解决这个问题?

回答

2

格式的字符串,并把它写:

s = ','.join(info) 
f.write(s + '\n') 
1

试试这个:

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() 
1

使用完整的,准备使用,序列化格式。例如:

import json 
x = ['a', 'b', 'c'] 
with open('/tmp/1', 'w') as f: 
    json.dump(x, f) 

文件内容:

["a", "b", "c"]