Q:

How to write data to a text file in python?

This is what I have so far:
def main():
    infoList = [] 
    count = 0

    while True:
        firstname = input('Please enter your first name: ')
        mystring = str(firstname)
        lastname = input('Please enter your last name: ')
        mystring2 = str(lastname)
        telephoneno = input('Please enter your telephone number: ')
        mystring3 = str(telephoneno)
        contiinue = input('Continue (y = yes): ')
        if contiinue == 'y':
            count = count + 1
        else:
            print ("File Written")
            break

        file = open('filename', 'a');
        file.write(data.to_string());
        file.close();

 main()

I'm trying to get the program to write the input as a text file, but allow new information added to be added to the text file, not to erase whats already been written.
Every time I try to run the program it say that there's a problem with the main() and also a name error, as data is not defined?

A:

To add to @Clodion's answer I would use the with keyword
def main():
    infoList = [] 
    count = 0

    while True:
        fnane = input('Please enter your first name: ')
        lname = input('Please enter your last name: ')
        tele = input('Please enter your telephone number: ')
        ok = input('Continue (y = yes): ')
        if ok == 'y':
            count = count + 1
        else:
            print ("File Written")
            break

    data = fname + lname + tele
    with open('filename', 'a') as file:
        file.write(data);

main()

