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 は正しいです。主な問題は、ファイルに書き込むたびにファイル全体を上書きしていることです。出力ファイルを読み取り可能にするために、各書き込みに \n を明示的に追加する必要があるという点でも、mehmattski は正しいです。

これを試して:

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 に答える