换行而不是插入

2024-04-29 00:25:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从文件中读取内容。我需要插入一行(如果还没有)后,检查了一个特定的关键字(函数)和存储函数名的某一行。我尝试在关键字匹配后插入它,但是下一行被替换而不是插入

原始文件

   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)

有人能建议我应该添加或删除什么以使事情正常进行吗


Tags: 文件函数inifislinenotfunction