换行而不是插入

时间:2017-12-01 01:08:28

标签: python list file append

我正在阅读文件中的内容。在检查具有特定关键字(函数)的特定行之后,我需要插入一行(如果尚未存在)并存储函数名称。我尝试在关键字匹配后插入它,但下一行被替换而不是插入。

原始文件

   function a:
     line not present

    function b:
       line is present :b

预期文件

  function a:
  line is present :a
  line not present.

  function b:
  line is present :b 

结果文件

  function a:
  line is present :a


   function b:
   line is present :b 

我尝试了以下代码:

  words=[]
  with open('sample.sv',"r") as f :
    for line in f:
      words.append(line)
      found=re.search('function',line)
      if found is not None:
         word=line.split(' ')[1]
         next_line=next(f)
         if 'line is present .*' not in next_line:
           words.append("line is present({p}) :".format(p=word)

有人可以建议我应该添加或删除什么来使事情有效。

0 个答案:

没有答案