Python以列表格式写入文件

时间:2013-06-21 18:47:11

标签: python python-3.x

我正在尝试编写一个程序,该程序将在文本文件中写入信息列表。这是我到目前为止的一个例子

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

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

格式化字符串并将其写入:

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

答案 1 :(得分: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()

答案 2 :(得分:1)

使用完整的,随时可用的序列化格式。例如:

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

文件内容:

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