将结果打印到文本文件

时间:2017-02-24 22:48:37

标签: python

我想将控制台中显示的结果从下面的循环打印到文本文件中。我已经尝试将此代码放在循环中,如示例中所示:

        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")

4 个答案:

答案 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)

问题是,每次迭代都是用write模式打开它 由于python documentation

  

'w'用于写入(如果文件已存在则截断文件)

出于您的目的,您应该使用"a"模式(追加)或打开文件不在周期