2017-02-24 112 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周期