[英]How do I iterate through a file containing a list of floating point numbers in Python?
I need to write a program that reads a file containing a list of floating-point numbers and counts how many of those numbers are larger than a user-specified threshold.我需要编写一个程序来读取包含浮点数列表的文件并计算这些数字中有多少大于用户指定的阈值。
numbers.txt -数字.txt -
This is my python code -这是我的 python 代码 -
in_file = open("numbers.txt", "r")
number = float(in_file.read()) # error in python
user_input = float(input("Threshold: "))
if number > user_input:
print(number)
in_file.close()
Python is unable to convert the string to a float because the numbers have a new line after each number and python is trying to convert that into a float. Python 无法将字符串转换为浮点数,因为数字在每个数字后都有一个新行,并且 python 正在尝试将其转换为浮点数。 I tried to change line 2 in my code to add a strip method but it still comes up with the same error.
我试图在我的代码中更改第 2 行以添加一个 strip 方法,但它仍然出现相同的错误。
for line in open("numbers.txt", "r"):
line = line.replace("\n","")
num = float(line)
im sure you can continue from here..我确定你可以从这里继续..
Try this:尝试这个:
with open('numbers.txt') as fp:
lst = [float(line.strip()) for line in fp if line.strip()]
user_input = float(input("Threshold: "))
for num in lst:
if num > user_input:
print(num)
You can try this workaround你可以试试这个解决方法
inputdata = []
with open('data.txt') as f:
for row in f:
try:
number = float(row)
inputdata.append(number)
except:
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.