0

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.

2
  • Perhaps a database would be a more robust (and simpler) solution? Commented Mar 18, 2022 at 20:33
  • 1
    why do you convert that string to an integer and then immediately convert it back to a string? qty = int(input('Quantity (in pounds): ')) and coffee_file.write(str(qty) + '\n')? also that error likely happens because you read the description only once outside of the loop, you need to place descr = coffee_file.readline() inside the while loop Commented Mar 18, 2022 at 20:35

2 Answers 2

1

Here's what is happening:

  1. The first line is read from the file and is treated as a description (which is correct.)
  2. The while loop starts.
  3. The next line is read from the file and is treated as a quantity (which is correct.)
  4. If the description does not match, the while loop repeats.
  5. The next line is read from the file and is treated as a quantity (which is wrong.)

You should read both the description and quantity inside the while loop, otherwise you get out of sync with the file contents.

Sign up to request clarification or add additional context in comments.

2 Comments

I just get AttributeError: 'builtin_function_or_method' object has no attribute 'readline'
@IMonV You've made some other mistake, and you haven't shown the updated code or the full error message, so I can't help...
0

I would put the description and the quantity on one line in the coffee.txt file and split them with a special character (like a "|" or a "="). When reading a line, you can then use something like:

(descr, qty) = line.split("|")

to assign the values to the variables.

Let's asume my coffee.txt file has this content:

amazon|8\nethiopia|25\nafrican pride|35\nkenya|14

I will write my search function like this:

def search_coffee():
    # 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.
    with open('coffee.txt', mode='r') as coffee_file:
        for line in coffee_file:
            (descr, qty) = line.split("|")
            # remove the \n from the quantity
            if qty.endswith("\n"):
                qty = qty[0:-1]
            # Compare the search term with the description
            if search == descr:
                found = True
                # If found, stop searching
                break

        if found:
            print(f"Record found!\n"
                  f"Description: {descr}\n"
                  f"Quantity: {qty}")
        else:
            print('That item was not found in the file.')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.