2011-04-25 88 views
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) 

如何將整個組保存到文本文件中。

回答

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

我討厭嵌套的'with'語句,它們使壓痕爆炸。幸運的是,你可以將它們放在更新的Python版本中:'打開('sirs.txt')作爲f,打開(「sirs1.txt」,「w」)作爲fw'。 – delnan 2011-04-25 11:40:37

+0

謝謝,但上面的方法創建了一個沒有空格的長字符串。有沒有辦法將它作爲列表保存到文件中? – moe 2011-04-25 15:02:49

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