Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

Yosef Fastow
Yosef Fastow
18,526 Points

Extra credit on shopping game. I can't find out how to save without overriding the previous one.

I'm using the open() to open shopping_list.txt and than json.jump(adding, lists) and than closing but when I run it and type in show or done it only returns the last entry and it looks like json is replacing the previous text every time.

So how could I save on the file without deleting the previous one.

def add():
    lists = open('shopping_list.txt', 'w')
    adding = input("What do you want to add to the list?")
    json.dump(adding, lists)
    lists.closed

2 Answers

Steven Parker
Steven Parker
215,958 Points

It's not the json that's replacing your file contents, it's your open.

:point_right: mode "w" opens a file for writing only. It overwrites the file if the file exists

If you want to add to an existing file, you want to open it with mode "a".

Yosef Fastow
Yosef Fastow
18,526 Points

That work's but I can't figure out how to turn the file int a list so we could alliterate aver each one individually. All I could get is all the items on one line like this: "Pizza""Melon""orange".

I tried append, split and list to make it into a list but then I get an AttributeError: '_io.TextIOWrapper' object has no attribute 'split'.

def show_list():
    num = 0
    print("")
    print("This is what you need to pick up from the store:")
    shopping_list = open('the_list.py', 'r')
    for shop in shopping_list:
        num += 1
        print(str(num) + ') ' + shop)
    print("")
    shopping_list.closed
Yosef Fastow
Yosef Fastow
18,526 Points

Don't worry I figured it out. I added ,read() to it to an string and then played around to get rite of all the ""becouse before it returned "beef ""orange ""pizza ""lemon ""apple "

I started shopping_list with one " so the functions won't delete the first letter of the first item in the list.

def show_list():
    num = 0
    print("")
    print("This is what you need to pick up from the store:")
    shopping_list = open('shopping_list.txt', 'r')
    the_list = shopping_list.read()
    the_list = the_list.split()
    del the_list[-1]
    for shop in the_list:
        num += 1
        print(str(num) + ') ' + shop[2:])
    print("")
    shopping_list.closed