Python以列表格式写入文件
我试图写一个程序,将写在一个文本文件的信息列表。这是我到目前为止的一个例子Python以列表格式写入文件,python,python-3.x,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()
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
如何解决此问题?格式化字符串并写入:
s = ','.join(info)
f.write(s + '\n')
格式化字符串并将其写入:
s = ','.join(info)
f.write(s + '\n')
试试这个:
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()
试试这个:
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()
使用完整的、随时可用的序列化格式。例如:
import json
x = ['a', 'b', 'c']
with open('/tmp/1', 'w') as f:
json.dump(x, f)
文件内容:
["a", "b", "c"]
使用完整的、随时可用的序列化格式。例如:
import json
x = ['a', 'b', 'c']
with open('/tmp/1', 'w') as f:
json.dump(x, f)
文件内容:
["a", "b", "c"]