Python - 只有最后一行被保存到文件中 [英] Python - Only last line is saved to file

查看:61
本文介绍了Python - 只有最后一行被保存到文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to output the result of my script into a text file. The script is working fine, the only problem is when results are saved into the text file (output.txt), only last line is being saved,not the whole thing? I'm not sure what I'm doing wrong here. any suggestions will be appreciated.

加油!

        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

推荐答案

你需要写

f = open("output.txt", "a")

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

This will append the file, rather than write over whatever else you put in it.

这篇关于Python - 只有最后一行被保存到文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆