将结果打印到文本文件
问题描述:
我想从下面的循环将我的控制台中显示的结果打印到文本文件中。我试图把这个代码在循环中所看到的例子:将结果打印到文本文件
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")
答
您应该使用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")
答
你应该确保你打开“out.txt”写外循环,而不是循环内
答
如果你想将文本写入一个文件,你应该使用.write()
方法的File
对象,如https://docs.python.org/2/tutorial/inputoutput.html中所述,而不是print
方法。