如何用python将变量及其值写入文本文件?

python将变量写入文本中
x=5
y=2
z=x+y
如何把把x、y、z及其值值写入到文本中?
想要的输出结果是:
x=5
y=2
z=7
下面这段哪里有问题?
x=5
y=2
z=x+y
f=open('test-i.dat','a+')
f.write(str("x=")+str(x)+'\n')
f.write(str("y=")+str(y)+'\n')
f.write(str("z=")+str(z)+'\n')
f.close()

你的缩进有问题,这样就好了。

x=5
y=2
z=x+y 
f=open('test-i.dat','a+')
f.write(str("x=")+str(x)+'\n')
f.write(str("y=")+str(y)+'\n')
f.write(str("z=")+str(z)+'\n')
f.close()

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-10-05

利用write函数写入文件,例如

a = ["a","b","c"]
file = open('test.txt','w')
for i in a:
    file.write(i)
file.close()
newfile = open("test.txt")
newfile.read()()

第2个回答  2014-08-18
看pyhton的文件操作
相似回答