发布时间:2019-07-31 09:29:34编辑:auto阅读(2938)
先看一个简单的例子:将变量写入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
54088
40848
35357
31014
25904
25644
24079
19610
15686
15166
1901°
1748°
1839°
1920°
1912°
2083°
2042°
1867°
1952°
1936°