python 添加文本内容到文件

添加文件内容(赋值为c1) 到 a.txt的最后一行
不要覆盖以前的内容

用a模式(append)打开文件,
f = open('test.txt','a')
f.write('c1')
f.close()追问

请教下 c1 = 123456
怎么换行写入a.txt
就是第一次执行 写入一行
第二次执行写入第二行

追答

f.write(str(c1)+"\n")

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

执行的python脚本:

#!/usr/local/python  
# coding=UTF-8  
import os  
  
file = open( "test.html", "r" )  
fileadd = open("test.txt","r")  
content = file.read()  
contentadd = fileadd.read()  
file.close()  
fileadd.close()  
pos = content.find( "</table>" )  
if pos != -1:  
        content = content[:pos] + contentadd + content[pos:]  
        file = open( "test.html", "w" )  
        file.write( content )  
        file.close()  
        print "OK"

第2个回答  2011-11-13
f = file('a.txt','a') #open for 'a'ppending
fi.write(c1)
f.close

#打开python的IDE,可以用help(file)查看file的内容
#有r、w、a,即读、写、附加3中追问

请教下 c1 = 123456
怎么换行写入a.txt
就是第一次执行 写入一行
第二次执行写入第二行

第3个回答  2011-11-13
open第二个参数修改为追加就可以啦追问

请教下 c1 = 123456
怎么换行写入a.txt
就是第一次执行 写入一行
第二次执行写入第二行

追答

write 和 writelines 有什么区别我忘记了
你可以加/n 还是\n 来着去换行

第4个回答  2011-11-16
f = open('test.txt','a')
相似回答