1、打开pycharm开发工具,在python项目中,定义列表变量b1并赋值。
2、使用列表中的方法,向列表b1的第二个位置,添加元素yhd,并打印结果。
4、检查代码发现,本来是想用insert,结果写成了index;修改代码方法,然后保存代码。
5、再次运行python文件,结果发现yhd添加到第二个位置。
按问题说明,可使用for line in open()方式完成,用一个循环读a文件内容,每读一行写入一个临时文件c,然后判断读出行内容,如果为特征行(b b b b),则以同样方式读b文件,逐行写入c,写入完成后继续写剩余a文件内容。最后删除a文件,把c改名为a,就可以完成要求,python资料介绍for line in open()这种方式是读写最快的方式。代码如下:
import oscf = open('c.txt','w')
for line in open('a.txt','r'):
cf.write(line)
if(line.strip() == 'b b b b'):
for nl in open('b.txt','r'):
cf.write(nl)
cf.close()
os.remove('a.txt')
os.rename('c.txt','a.txt')
执行结果:
a.txt内容如下
a a a a
b b b b
1 1 1 1
2 2 2 2
3 3 3 3
c c c c
fp = open("test.txt")str = fp.read()
str = "hi!\n" + str
print str
fp.close()
fp = open("test.txt", "w")
fp.write(str)
fp.close()
把test.txt改成自己的文件名,str后面的hi\n改成自己要加的内容