Ask coding questions

← Back to all posts
shopping list help
RyanWatstein (3)

Create a program that reads data from a file and writes data to the file.... Use a list to store the data read from the file.... The data that you will have is a grocery list. Store data read from file in a list. The user should be able to see the list and add to it.

How do I accomplish this?

I have attached my code

RyanWatstein (3)

This code works to view the txt file, but I need the user to be able to add items to the shopping list. How do I do that?


you can take an array and have it write to the file like this:

things_to_write = ["toast","cereal","watermelon"]

old_file = open("grocery_list.txt","r").read()      # read the file (and convert it to a mutable string) before you can manipulate anything

# add the new things to the string
for i in things_to_write:
    old_file += i
    old_file += "\n"

with open("grocery_list.txt","w") as text_file:   # (the second parameter, "w", is what lets you write to the file)
    for i in old_file:
        text_file.write(i)  # rewriting everything to the file

I think this answers your question :)

mwilki7 (1134)

To read everything from a file you can try:

lines = []
with open('your_file_name.txt') as file:
  for line in file:

You can put a special character or string at the start of the grocery list so you know where it starts in the file (in this example I'm looking for 'START'):

grocery_list_start = 0
for i in range(0, len(lines)):
    if (line == 'START'):    # ok i found where my list starts
        grocery_list_start = i + 1

# pick up where I left off
for i in range(grocery_list_start, len(lines)):