2015-03-25 182 views
0

我正在嘗試創建一個腳本,它以文件作爲輸入,查找所有電子郵件地址並將它們寫入指定文件。使用Python打印輸出到文件

基於其他類似的問題,我已經結束了與此:

import re 

    Input = open("inputdata.txt", "r") 
    regex = re.compile("\b[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,4}\b") 
    Logfile = "Result.txt" 


     for line in Input: 
      query = regex.findall(line) 
      for line in query: 
       print >>Logfile, query 

我到底做錯了什麼?這不輸出。 我猜測主要問題是「對於查詢中的行:」,我試圖改變沒有任何運氣。

乾杯!

編輯:我改變了腳本,如下所示,用「打印(查詢)」代替。 我仍然沒有得到任何輸出。 當前的腳本是:

import re 

Input = open("Inputdata.txt", "r") 
regex = re.compile("\b[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,4}\b") 
# logfile = "Result.txt" 

for line in Input: 
    query = regex.findall(line) 
    for line in query: 
     with open("Result.txt", "a") as logfile: 
      logfile.write(line) 

它輸出什麼,並告訴我: 「NameError:名字 」日誌文件「 沒有定義」。 是什麼原因造成的,這是沒有輸出的原因嗎?

+0

關於您的編輯:我沒有收到該代碼的名稱錯誤;你確定你正在使用這個確切的代碼嗎?請注意,我將變量從'Logfile'更改爲'logfile'(即小寫),以符合編碼約定。此外,您不必在每次迭代中重新打開該文件。將'with ...'行移到循環的頂部。 – 2015-03-25 12:08:25

回答

1

您的Logfile變量只是名稱的文件,而不是實際的file對象。此外,您應該使用with在完成後自動關閉文件。試試這個:

with open("Result.txt", "a") as logfile: 
    print >>logfile, "hello world" 
    print >>logfile, "another line" 

但需要注意的是Python 3.x中,語法是不同的,因爲print不再是一個聲明,但a function

with open("Result.txt", "a") as logfile: 
    print("hello world", file=logfile) 
    print("another line", file=logfile) 

因此,而不是重定向print,最好的選擇可能是直接將write添加到文件中:

with open("Result.txt", "a") as logfile: 
    logfile.write("hello world\n") 
    logfile.write("another line\n") 
+0

非常感謝。 工作腳本如下所示,現在輸出正確: import re Input = open(「Input.txt」,「r」) regex = re.compile(「\ b [A-Z0-9._ %+ - ] + @ [A-Z0-9 .-] + \。(AZ){2,4} \ b「) #logfile = open(」Result.txt「,」a「) 以開放(」Result.txt「,」a「)作爲日誌文件: 輸入: query = regex.findall(line) for input in:輸入: logfile.write(query) – Krisem 2015-03-25 12:33:37

0

我不認爲,與print你可以寫入文件,而不必將輸出重定向到一個文件。我猜你已經使用了print,你只需要輸出重定向。

假設您的python腳本位於文件test.py中。 更換行:

print >>Logfile, query 

只:

print query 

而從終端/ CMD,運行腳本是這樣的:

python test.py >> Result.txt 

這被稱爲輸出重定向。