pythonfor-loopconsole.writeline

I cannot let the list write in txt (python)


I want to use writelines() to let the list write in txt, but after running, there's nothing in my txt. What's wrong with my code?

Help me if you could. Thank you!

example list(records): [['flower', '200'], ['ham', '60'], ['van', '150']]

I want to write in the txt as below:

flower 200

ham 60

van 50

my code:

def save(initial_money, records): # I need both so don't change.
    with open('records.txt', 'w') as f: 
        first_line = str(initial_money) + "\n"
        f.write(first_line)
        return initial_money
        L = []
        for rec, amt in records:
            all_rec = str(rec) + " " + str(amt) + "\n"
            L.append(all_rec)
        f.writelines(records) # must use writelines
        return records

Solution

  • This should do:

    def save(initial_money, records):
        with open('records.txt', 'w') as f: 
            first_line = str(initial_money) + "\n"
            f.write(first_line)
            for rec, amt in records:
                f.write(str(rec) + " " + str(amt) + "\n")
    

    The first return closes the function, you don't need second return either, records is available as argument.

    If you insist on using writelines, you can modify it like below:

    def save(initial_money, records):
        with open('records.txt', 'w') as f: 
            first_line = str(initial_money) + "\n"
            f.write(first_line)
            L = []
            for rec, amt in records:
                L.append(str(rec) + " " + str(amt) + "\n")
            f.writelines(L)