0

I have written a simple program with file handling to simulate an inventory. The user can pick something up, drop or view the inventory. The drop function isn't working correctly.

f = open("inv.data.txt", "a+")
f.seek(0)
test = f.readlines()
inventory = input("")

if "inv pick" in inventory: #Example "inv pick X"
    removeSpaces = inventory.split(" ")
    itemHolder = removeSpaces[2]
    final = itemHolder + "\n"
    f.write(final)

elif "inv drop" in inventory: #Example: "inv drop X"
    remove =  inventory.split(" ")
    itemHolder1 = remove[2]
    thefinal = itemHolder1 + "\n"
    test = test.remove(thefinal)

elif inventory == "inv": #Show inventory
    for i, item in enumerate(test):
        afterRemove = item.strip()
        print("{}. {}".format(i + 1, afterRemove))

f.close()

I have tried writing out the list in the condition for removing items, and the .remove function is working but the file is not being updated after I have removed the item. I assume I have to write back to the file after I have removed something but it doesn't work with: f.write(test). Any suggestions?

Thanks!

Riggs
  • 99
  • 2
  • 9
  • Where are you writing the changes? removing something from the list has no bearing whatsoever on the file – Padraic Cunningham Mar 27 '16 at 16:41
  • Also a+ is open for reading and writing, any writes will be appended to the end of thh file, what you want is to write to a temporary file http://stackoverflow.com/questions/30481308/overwritting-characters-from-a-file-in-python/30481339#30481339 – Padraic Cunningham Mar 27 '16 at 17:08
  • You need to revisit the part of the Python tutorial that [deals with files](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files). – Roland Smith Mar 27 '16 at 18:57
  • You will have to save the file, else it will keep giving you whatever was in it before – h_e_u_r_e_k_a Mar 27 '16 at 19:40
  • Yes @h_e_u_r_e_k_a, but how can I do that? I guess I have to check out Cunningshams link. – Riggs Mar 27 '16 at 20:24
  • It seems you have to do that. It's quite a long answer, but it's worth it. I think it will solve your problem. – h_e_u_r_e_k_a Mar 27 '16 at 21:04
  • Ait, got it working. Thanks for help, boyz! – Riggs Mar 28 '16 at 13:37

0 Answers0