在文本文件的指定位置插入行 [英] Inserting Line at Specified Position of a Text File

查看:138
本文介绍了在文本文件的指定位置插入行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,如下所示:

I have a text file which looks like this:

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

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

Now I want to insert 'foo bar' between 'foo1 bar3' and '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)

这对我有用,但是看起来很丑.

This works for me, but looks rather ugly.

推荐答案

在Python中对文件进行伪替换"更改的最佳方法是使用标准库中的fileinput模块:

The best way to make "pseudo-inplace" changes to a file in Python is with the fileinput module from the standard library:

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作为备份扩展名,但在更改成功完成后也将其删除

You can also specify a backup extension if you want to keep the old version around, but this works in the same vein as your code -- uses .bak as the backup extension but also removes it once the change has successfully completed.

除了使用正确的标准库模块之外,此代码还使用了更简单的逻辑:在每次以foo1开头的行之后插入"foo bar"行,就只需要一个布尔值(是否在这样的运行中) ?),可以仅基于当前行是否以此方式无条件设置有问题的布尔值.如果您想要的精确逻辑与此代码略有不同(这是我从您的代码中推论得出的),那么就不难相应地调整此代码.

Besides using the right standard library module, this code uses simpler logic: to insert a "foo bar" line after every run of lines starting with foo1, a boolean is all you need (am I inside such a run or not?) and the bool in question can be set unconditionally just based on whether the current line starts that way or not. If the precise logic you desire is slightly different from this one (which is what I deduced from your code), it shouldn't be hard to tweak this code accordingly.

这篇关于在文本文件的指定位置插入行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆