Skip to main content
 首页 » 编程设计

python之将整个正则表达式组导出到文本文件

2024年09月03日27lautakyan007

当我打印组“print(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) 

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

请您参考如下方法:

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()