为了账号安全,请及时绑定邮箱和手机立即绑定

在文本文件的指定位置插入行

在文本文件的指定位置插入行

www说 2019-10-18 11:01:03
我有一个看起来像这样的文本文件:blah blahfoo1 bar1foo1 bar2foo1 bar3foo2 bar4foo2 bar5blah blah现在我要'foo bar'在'foo1 bar3'和之间插入'foo2 bar4'。这是我的方法:import shutiltxt = '1.txt'tmptxt = '1.txt.tmp'with open(tmptxt, 'w') as outfile:    with open(txt, 'r') as infile:        flag = 0        for line in infile:            if not line.startswith('foo1') and flag == 0:                outfile.write(line)                continue            if line.startswith('foo1') and flag == 0:                flag = 1                outfile.write(line)                continue            if line.startswith('foo1') and flag == 1:                outfile.write(line)                continue            if not line.startswith('foo1') and flag == 1:                outfile.write('foo bar\n')                outfile.write(line)                flag = 2                continue            if not line.startswith('foo1') and flag == 2:                outfile.write(line)                continueshutil.move(tmptxt, txt)这对我有用,但是看起来很丑。
查看完整描述

3 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

改编Alex Martelli的示例:


import fileinput

for line in fileinput.input('1.txt', inplace=1):

 print line,

 if line.startswith('foo1 bar3'):

     print 'foo bar'


查看完整回答
反对 回复 2019-10-18
?
开心每一天1111

TA贡献1836条经验 获得超13个赞

回想一下,迭代器是一流的对象。它可以用于多个for语句。


这是一种无需大量复杂外观的if语句和标志即可解决此问题的方法。


with open(tmptxt, 'w') as outfile:

    with open(txt, 'r') as infile:

        rowIter= iter(infile)

        for row in rowIter:

            if row.startswith('foo2'): # Start of next section

                 break

            print row.rstrip(), repr(row)

        print "foo bar"

        print row

        for row in rowIter:

            print row.rstrip()


查看完整回答
反对 回复 2019-10-18
  • 3 回答
  • 0 关注
  • 755 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信