将整个正则表达式组导出到文本fi

2024-10-01 17:31:30 发布

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

当我打印组“打印(a)”时,会显示整个组。当我把它保存到一个文本文件“open(“sirs1.txt”,“w”).write(a)”文件中只保存最后一行。在

import re

def main():
f = open('sirs.txt')
for lines in f:
    match = re.search('(AA|BB|CC|DD)......', lines)
    if match:
        a = match.group()
        print(a)
        open("sirs1.txt", "w").write(a)

如何将整个组保存到文本文件中。在


Tags: 文件inimportretxtformaindef
3条回答

open命令创建一个新文件,因此您每次都要创建一个新文件。在

尝试在for循环之外创建文件

import re
def main():
    with open('sirs.txt') as f:
        with open("sirs1.txt", "w") as fw:
            for lines in f:
                match = re.search('(AA|BB|CC|DD)......', lines)
                if match:
                    a = match.group()
                    print(a)
                    fw.write(a)

您需要在每个字符串后添加一个换行符,以便在单独的行上打印:

import re

def main():
   f = open('sirs.txt')
   outputfile = open('sirs1.txt','w')
   for lines in f:
      match = re.search('(AA|BB|CC|DD)......', lines)
      if match:
          a = match.group()
          print(a)
          outputfile.write(a+'/n')
   f.close()
   outputfile.close()

nosklo是正确的主要问题是每次写入时都会覆盖整个文件。mehmattski也是正确的,您还需要显式地将\n添加到每次写入中,以便使输出文件可读。在

试试这个:

enter code here

import re

def main():
  f = open('sirs.txt') 
  outputfile = open('sirs1.txt','w')

  for lines in f:
    match = re.search('(AA|BB|CC|DD)......', lines)
    if match:
      a = match.group()
      print(a)
      outputfile.write(a+"\n")

  f.close()
  outputfile.close()

相关问题 更多 >

    热门问题