Python - 仅最后一行保存到文件中

use*_*436 2 python python-2.7

我正在尝试将脚本的结果输出到文本文件中。该脚本工作正常,唯一的问题是当结果保存到文本文件(output.txt)中时,仅保存最后一行,而不是整个内容?我不确定我在这里做错了什么。任何建议将不胜感激。

欢呼!

        try:

            if 'notavailable' not in requests.get('url' + str(service) + '&username=' + str(username), headers={'X-Requested-With': 'XMLHttpRequest'}).text:
                result = service + '\t' + " > " + username + " > " 'Available'
                print  result
                f = open("output.txt", "w")              
                f.write(result + "\n")
                f.close()

            else:
                print service + '\t' + " > " + username + " > " 'Not Available'

        except Exception as e:
            print e
Run Code Online (Sandbox Code Playgroud)

Dav*_*ave 5

你需要写

f = open("output.txt", "a")
Run Code Online (Sandbox Code Playgroud)

这将附加该文件,而不是覆盖您放入其中的任何其他内容。