I keep getting the ValueError: could not convert string to float: 'Coffee two\n' This always occurs in the 2nd coffee that was inputted.
Here is the first part of the code, just for testing purposes, I'd use "Coffee one" and "10" then "Coffee two" and "20" when you're asked for input.
Program one:
# This program adds coffee inventory records to
# the coffee.txt file.
another = 'y'
coffee_file = open('coffee.txt', 'a')
while another == 'y' or another == 'Y':
print('Enter the following coffee data:')
descr = input('Description: ')
qty = int(input('Quantity (in pounds): '))
coffee_file.write(descr + '\n')
coffee_file.write(str(qty) + '\n')
print('Do you want to add another record?')
another = input('Y = yes, anything else = no: ')
coffee_file.close()
print('Data appended to coffee.txt.')
Program two:
# This program allows the user to search the
# coffee.txt file for records matching a
# description.
def main():
# Create a bool variable to use as a flag.
found = False
# Get the search value.
search = input('Enter a description to search for: ')
# Open the coffee.txt file.
coffee_file = open('coffee.txt', 'r')
# Read the first record's description field.
descr = coffee_file.readline()
# Read the rest of the file.
while descr != '':
# Read the quantity field.
qty = float(coffee_file.readline())
# Strip the \n from the description.
descr = descr.rstrip('\n')
# Determine whether this record matches
# the search value.
if descr == search:
# Display the record.
print('Description:', descr)
print('Quantity:', qty)
print()
# Set the found flag to True.
found = True
# Read the next description.
descr = coffee_file.readline()
# Close the file.
coffee_file.close()
# If the search value was not found in the file
# display a message.
if not found:
print('That item was not found in the file.')
# Call the main function.
main()
The error always occurs at this line, qty = float(coffee_file.readline()) I have tried removing it, changing the float to string, and also changing the code to work without main() and I'm not sure where to go from there.
qty = int(input('Quantity (in pounds): '))andcoffee_file.write(str(qty) + '\n')? also that error likely happens because you read the description only once outside of the loop, you need to placedescr = coffee_file.readline()inside the while loop