2017-02-24 109 views
0

我想從下面的循環將我的控制檯中顯示的結果打印到文本文件中。我試圖把這個代碼在循環中所看到的例子:將結果打印到文本文件

 f = open('out.txt', 'w',) 
     sys.stdout = f 

然而,當這是在環路我只得到一個結果集,而不是完整預期。

wordlist = input("What is your word list called?") 
f = open(wordlist) 
l = set(w.strip().lower() for w in f) 
chatlog = input("What is your chat log called?") 
with open(chatlog) as f: 
    found = False 
    for line in f: 
     line = line.lower() 
     if any(w in line for w in l): 
      print (l) 
      print(line) 
      found = True 
      f = open('out.txt', 'w',) 
      sys.stdout = f 
    if not found: 
     print("not here") 

回答

0

您應該使用write()函數將結果寫入文件。

代碼應該是因爲:

wordlist = input("What is your word list called?") 
f = open(wordlist) 
l = set(w.strip().lower() for w in f) 
chatlog = input("What is your chat log called?") 

with open(chatlog) as f: 
    found = False 
    file = open("out.txt", "w") 
    for line in f: 
     line = line.lower() 
     if any(w in line for w in l): 
      found = True 
      file.write(line) 
    if not found: 
     print("not here") 
0

你應該確保你打開「out.txt」寫外循環,而不是循環內

0

的問題是,每次迭代你寫模式 由於python documentation打開它:

「W」寫(截斷如果文件它已經存在)

爲了你的目的你應該用"a"模式(追加)或打開文件ou t週期