2

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

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

4

3 回答 3

2

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()
于 2011-04-26T10:23:25.530 回答
1

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)
于 2011-04-25T11:35:52.197 回答
0

您需要在每个字符串之后添加一个换行符以使它们在单独的行上打印:

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()
于 2011-04-25T21:31:57.887 回答