[英]Python - Only last line is saved to file
我正在尝试将脚本的结果输出到文本文件中。 脚本工作正常,唯一的问题是当结果保存到文本文件 (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
你需要写
f = open("output.txt", "a")
这将附加文件,而不是覆盖您放入其中的任何其他内容。
在每次迭代中,您都在打开文件、擦除其内容、写入和关闭。 最好只打开一次:
f = open('output.txt', 'w')
# do loop
f.write(stuff)
f.close()
或者,更好:
with open('output.txt', 'w') as f:
while loop:
f.write(stuff)
这种方法不仅更干净,而且性能更好,因为您可以缓存文件的内容,并使用最少的操作系统调用。
我将进行大胆的猜测并假设所有这些代码都发生在一个循环中。 每次循环时,您都会多写一行,但最后只有最后一行。
如果这是问题所在,那么问题就在这里:
f = open("output.txt", "w")
当您以'w'
模式打开文件时,会截断任何现有文件。
要解决此问题,请在循环外打开文件一次,而不是一遍又一遍地打开文件,或者以'a'
模式或'r+'
模式或其他不会截断文件'a'
模式打开它。
open
函数的文档或交互式解释器中的内联帮助解释了所有不同模式的含义。
你试过参数 'a' 所以: f = open("output.txt", "a")
这将在末尾打开带有指针的文件。 http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.