Q:

Python - Only last line is saved to file

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.
Cheer!
        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

A:

you need to write 
f = open("output.txt", "a")

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

A:

In every iteration you are opening the file, erasing its content, writing and closing. It is much better to open it only once:
f = open('output.txt', 'w')
# do loop
    f.write(stuff)
f.close()

Or, much better:
with open('output.txt', 'w') as f:
    while loop:
       f.write(stuff)

This method is not only cleaner, but also performs much better, as you can cache the contents of the file, and use the minimal number of OS calls.

