在文本文件中指定位置插入线(Inserting Line at Specified Position

2019-06-18 23:15发布

我有一个文本文件,它看起来像这样:

blah blah
foo1 bar1
foo1 bar2
foo1 bar3
foo2 bar4
foo2 bar5
blah blah

现在,我想插入'foo bar'之间'foo1 bar3''foo2 bar4'

这是我做的:

import shutil

txt = '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)
                continue

shutil.move(tmptxt, txt)

这对我的作品,但看起来比较难看。

Answer 1:

让“伪就地”更改为Python中的文件的最佳方法是使用fileinput从标准库模块:

import fileinput

processing_foo1s = False

for line in fileinput.input('1.txt', inplace=1):
  if line.startswith('foo1'):
    processing_foo1s = True
  else:
    if processing_foo1s:
      print 'foo bar'
    processing_foo1s = False
  print line,

如果你想保留旧版本周围还可以指定备份的扩展,但这部作品在同样的代码-使用.bak作为备份扩展也删除它一旦改变已成功完成。

除了使用正确的标准库模块,该代码使用简单的逻辑:插入一个"foo bar"开始的代码行的每次运行后线foo1 ,一个布尔值是所有你需要(我是这样的运行内部或没有?)和布尔问题可以无条件只是基于当前行是否将启动的方式或不设置。 如果你想要的精确的逻辑是这样一个(这是我从你的代码推断)略有不同,它不应该是很难相应调整此代码。



Answer 2:

适应亚历马尔泰利的例子:

import fileinput
for line in fileinput.input('1.txt', inplace=1):
 print line,
 if line.startswith('foo1 bar3'):
     print 'foo bar'


Answer 3:

回想一下,一个迭代是第一类对象。 它可以在多个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()


文章来源: Inserting Line at Specified Position of a Text File