在特定行之后添加行

时间:2014-01-22 14:24:13

标签: python

我正在尝试将特定行添加到文件中的特定区域。 我正在使用这个:

new_file = open("file.txt", "r+")
 for line in new_file:
  if line == "; Include below":
     line = line + "\nIncluded text"
     new_file.write(line)
  else:
     new_file.write(line)

但由于某种原因,我file.txt的内容是重复的。

编辑:如果我的文件如下:

blablablablablablabal
balablablabalablablbla
include below
blablablablablabalablab
ablablablabalbalablaba

我想让它看起来像:

blablablablablablabal
balablablabalablablbla
include below
included text
blablablablablabalablab
ablablablabalbalablaba

3 个答案:

答案 0 :(得分:12)

阅读时无法安全地写入文件,最好将文件读入内存,更新文件并将其重写为文件。

with open("file.txt", "r") as in_file:
    buf = in_file.readlines()

with open("file.txt", "w") as out_file:
    for line in buf:
        if line == "; Include this text\n":
            line = line + "Include below\n"
        out_file.write(line)

答案 1 :(得分:1)

这就是我所做的。

def find_append_to_file(filename, find, insert):
    """Find and append text in a file."""
    with open(filename, 'r+') as file:
        lines = file.read()

        index = repr(lines).find(find) - 1
        if index < 0:
            raise ValueError("The text was not found in the file!")

        len_found = len(find) - 1
        old_lines = lines[index + len_found:]

        file.seek(index)
        file.write(insert)
        file.write(old_lines)
# end find_append_to_file

答案 2 :(得分:0)

使用sed

$ sed '/^include below/aincluded text' < file.txt

说明:

  • /^include below/:匹配以^
  • 开头的每一行(include below
  • a:附加换行符和以下文字
  • includeed texta附加
  • 的文字

编辑:使用Python:

for line in open("file.txt").readlines():
    print(line, end="")
    if line.startswith("include below"):
        print("included text")