python, write the contents of a list to a text file

Chris Andrews picture Chris Andrews · Jul 7, 2016 · Viewed 9.8k times · Source

I created a program in python that is used to create/edit user generated lists. I tried to create a save function that will save a list to a text file, but I'm having a problem. It will create the text file but not write the content of the list to the text file.

#!/usr/bin/python
user_list = []
def banner():
    logo = open('chlogo2', 'r')
    for line in logo:
        print line.strip('\n')
    logo.close
    main(user_list)
def save(user_list):
    print "\nENTER A SAVE NAME.\nTHIS WILL BE SAVED AS A .TXT FILE.\n"
    w = ("saves/" + raw_input("CNG>SAVE NAME> ") +".txt")
    wr = open(w, 'w')
    for i in user_list:
        i.write(user_list, '\n')
    main(user_list)
def prt(user_list):
    print '\nCURRENT LIST -\n'
    r = user_list
    for line in r:
        print line.strip('\n')
    main(user_list)
def add(user_list):
    print "\nTYPE AN ENTRY IN A 'POSITION' then 'ENTRY' FORMAT\nPRESS 'ENTER' WITHOUT AN INPUT TO RETURN TO THE MAIN FUNTION\n"
    try:
        x = int(raw_input("CNG>ADD>P> "))
        y = raw_input("CNG>ADD>E> ")
        x -= 1
        user_list.insert(x, y)
        add(user_list)
    except:
        main(user_list)
def main(user_list):    
    option = open('options')
    for line in option:
        print line.strip('\n')
    option.close
    opt = raw_input("CHG> ")


    if opt == "list":
        prt(user_list)
    elif opt == 'banner':
        banner()
    elif opt == 'exit':
        print ' '
    elif opt == 'empty':
        user_list = []
    elif opt == 'add':
        add(user_list)
    elif opt == 'save':
        save(user_list)     

if __name__ == "__main__":
    banner()    

Answer

sehrob picture sehrob · Jul 7, 2016

Your problem is in this line:

for i in user_list: i.write(user_list, '\n')

Change it to this:

for i in user_list:
    wr.write(i, '\n')

EDIT: And remove user_list parameter from all of your functions because it is a global variable and you can access it from within your any function. This may also be a reason why your list not getting saved.