【问题标题】:Adding lines after specific line在特定行之后添加行
【发布时间】:2014-01-22 14:24:12
【问题描述】:

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

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

【问题讨论】:

标签: python


【解决方案1】:

读取时不能安全地写入文件,最好将文件读入内存,更新并重写到文件。

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)

【讨论】:

    【解决方案2】:

    这就是我所做的。

    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
    

    【讨论】:

      【解决方案3】:

      使用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")
      

      【讨论】:

      • 确切地说会是什么样子?
      • 完全按照您的要求。试试看。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多