I am new to Python and trying to figure out where I am going wrong in my current program. I am trying to write it so that it will check for a specific text file ("HomeInventory.txt") and perform different tasks based on if it does or does not exist. For example, if it does exist, then it would ideally ask the user if they want to add to the data already there and if it doesn't, then ask them if they want to create a new file. I thought what I had was getting my close, but it never seems to recognize that the file does exist. Any help is greatly appreciated. Here is my code:
from pathlib import Path
tupleRow = ( "","" )
tupleTable = ()
while(True):
# Obtain user input (2 different variables)
nameVal = str(input("Enter the name of a household item: "))
inputName = str(nameVal).upper()
inputValue = float(input("Enter the value of your item: "))
# Format values entered to appear like currency
# NOTE: Because I use float as input, I only need one "0"
# at the end
tempVal = str(inputValue)
finalVal = "$" + tempVal + "0"
# Stores each new input into it's correct tuple
tupleRow = (inputName, finalVal)
# 2. Ask the user for new entries and stores
# them in the 2-dimensional Tuple.
continueMsg = str(input("Do you have more items to enter? Y/N: ").upper())
if(continueMsg == "Y"):
continue
else:
break
tupleTable += tupleRow
myFile = Path("%~dp0HomeInventory.txt")
if(myFile.is_file() == False):
createFile = str(input("HomeInventory.txt does not exist yet, do you want to create it? Y/N: ").upper())
if(createFile == "Y"):
objFile = open("HomeInventory.txt", "a+")
# Conditional Header
for line in objFile:
if ("Item, Value" in line):
objFile.write(str(tupleTable).strip("(" ")" "'" "'"))
objFile.close()
else:
row0 = str("Item, Value")
objFile.write(str(row0 + '\n'))
objFile.write(str(tupleTable).strip("(" ")" "'" "'"))
objFile.close()
else:
print("Y'all come back later. Y'hear? ")
elif(myFile.is_file() == True):
overrideMsg = str(input("HomeInventory.txt already exists. Save new data here? Y/N: ").upper())
if(overrideMsg == "Y"):
objFile = open("HomeInventory.txt", "a")
# Conditional Header
for line in objFile:
if ("Item, Value" in line):
objFile.write(str(tupleTable).strip("(" ")" "'" "'"))
objFile.close()
else:
row0 = str("Item, Value")
objFile.write(str(row0 + '\n'))
objFile.write(str(tupleTable).strip("(" ")" "'" "'"))
objFile.close()
else:
print("Y'all come back later. Y'hear? ")