我想将控制台中显示的结果从下面的循环打印到文本文件中。我已经尝试将此代码放在循环中,如示例中所示:
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 :(得分:0)
你应该确保打开'out.txt'以便在循环外写入,而不是在循环内部
答案 1 :(得分:0)
如果要将文本写入文件,则应使用https://docs.python.org/2/tutorial/inputoutput.html中指定的.write()
对象的File
方法,而不是print
方法
答案 2 :(得分: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")
答案 3 :(得分:0)