简体   繁体   English

如何修复 ValueError: could not convert string to float: in python

[英]How to fix the ValueError: could not convert string to float: in python

I keep getting the ValueError: could not convert string to float: 'Coffee two\n' This always occurs in the 2nd coffee that was inputted.我不断收到ValueError: could not convert string to float: 'Coffee two\n'这总是发生在输入的第二杯咖啡中。 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.这是代码的第一部分,仅用于测试目的,当您被要求输入时,我会使用“Coffee one”和“10”,然后是“Coffee two”和“20”。

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 = float(coffee_file.readline())我试过删除它,将浮点数更改为字符串,还更改代码以在没有 main() 的情况下工作,我不确定 go 在哪里从那里。

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. while 循环开始。
  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.如果描述不匹配,则重复 while 循环。
  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.您应该阅读 while 循环的描述和数量,否则您将与文件内容不同步。

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 "=").我会将描述和数量放在 coffee.txt 文件的一行中,并用特殊字符(如“|”或“=”)将它们分开。 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:假设我的 coffee.txt 文件包含以下内容:

amazon|8.nethiopia|25\nafrican pride|35\nkenya|14亚马逊|8.nethiopia|25\nafrican pride|35\nkenya|14

I will write my search function like this:我会这样写我的搜索 function:

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.')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何修复 ValueError :无法将字符串转换为浮点数:在 Python 中 - how to fix ValueError :could not convert string to float: in Python 如何修复“ValueError:无法将字符串转换为浮点数:'East'”(Python) - How to fix "ValueError: could not convert string to float: 'East'" (Python) 如何使用tkinter修复Python中的“ ValueError:无法将字符串转换为float:” - How to fix “ValueError: could not convert string to float:” in Python with tkinter 如何修复“ValueError:无法将字符串转换为浮点数”? - How to fix “ValueError: could not convert string to float”? 如何修复“ValueError:无法将字符串转换为浮点数” - How to fix “ValueError: could not convert string to float” 如何修复此错误:ValueError:无法将字符串转换为浮点数:'A' - How to fix this error: ValueError: could not convert string to float: 'A' 如何修复错误 ValueError: could not convert string to float in a NLP project in python? - how to fix the error ValueError: could not convert string to float in a NLP project in python? ValueError:无法将字符串转换为浮点数:'F' python - ValueError: could not convert string to float: 'F' python ValueError:无法将字符串转换为float'jpg'Python - ValueError: could not convert string to float 'jpg' Python Python中的“ValueError:无法将字符串转换为float” - “ValueError: could not convert string to float” in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM