发布时间:2019-07-31 09:29:34编辑:auto阅读(2547)
先看一个简单的例子:将变量写入txt文本中
f = open('E:/test.txt','w')
f.write('hello world!')
Out[3]: 12
f.close()
那么如何将变量按行写入呢?
在'w'写入模式下,当我们下次写入变量时,会覆盖原本txt文件的内容,这肯定不是我们想要的。TXT有一个追加模式'a',可以实现多次写入:
f = open('E:/test.txt','a')
f.write('the second writing...')
Out[6]: 21
f.close()
如果要按行写入,我们只需要再字符串开头或结尾添加换行符'\n'即可:
f = open('E:/test.txt','a')
f.write('\nthe third writing...')
Out[9]: 21
f.close()
如果想要将多个变量同时写入一行中,可以使用writelines()函数:
f = open('E:/test.txt','a')
f.writelines(['\nthe fourth writing...',',','good'])
f.close()
参考:
上一篇: python中list的四种查找方法
下一篇: 启动Python
51721
51380
41813
38584
33065
30074
28745
23741
23651
22019
2242°
2927°
2445°
2389°
2975°
2394°
3200°
5259°
5072°
3626°