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!