![](/img/trans.png)
[英]Python read txt file as input: IndexError: list index out of range?
[英]List index out of range when trying to read in a txt file in Python
我想在 Python 中读取一个 txt 文件。 文本文件由 3 列组成,所有列都用“,”分隔。 一列表示 ID,一列表示随机浮点数,一列表示分配的属性(solo,not solo,acc)。
我的目标是将“solo”和“acc”的值转换为“not solo”,然后计算变量 y。
要求用户输入 ID(数字)。然后我想将 txt 文件的行转换为列表并搜索剩余的值,例如用户输入:45 --> 我想搜索分配的值,然后将其转换为 'not solo' 并计算 y。 最后,我想以“非独奏”为单位打印分配的值以及 y 计算。
但是,当我尝试查找值时,我收到一条错误消息,指出我的列表索引超出范围。 有谁知道如何解决这个问题?
我浏览了几个小时,但找不到有效的解决方案。
太感谢了!
import math
fobj = open('test.txt', 'r')
file_content = fobj.readline()
fobj.close()
for file in file_content:
file = file.strip()
file_list = file.split(',')
ID_q = int(input("Please enter number [else enter 'finished']:"))
ID = ID_q + 1
if ID_q != "finished":
output = "Your ID {} is assigned to following values: ".format(ID_q)
print(output)
#Now the fun part starts!
chosen_line = [ID]
for position, line in enumerate(file_content):
if position in chosen_line:
file_line = chosen_line.split(',')
ID_inline = file_list[0]
print(ID_inline)
if file_list[2] == 'solo':
x = float((float(file_list[1])) * (math.pi/180))
x_result = float("not solo: {0}".format(x))
x_result = round(x_result, 2)
y = float(math.sin((6*(float(file_list[1])))-(3*math.cos((float(file_list[1]))))))
function = float("f(x) = {0}".format(y))
function = round(function, 2)
print(x_result)
print(function)
elif file_list[2] == 'acc':
x = float((float(file_list[1])) * (math.pi/200))
x_result = float("not solo: {0}".format(x))
x_result = round(x_result, 2)
y = float(math.sin((6*(float(file_list[1])))-(3*math.cos(float(file_list[1])))))
function = float("f(x) = {0}".format(y))
function = round(function, 2)
print(x_result)
print(function)
else:
x = ID
y = float(math.sin((6*(float(file_list[1])))-(3*math.cos(float(file_list[1])))))
function = float("f(x) = ".format(y))
function = round(function, 2)
print(x)
print(function)
else:
print("Bye.")
当你这样做时:
fobj = open('test.txt', 'r')
file_content = fobj.readline()
fobj.close()
您只读取一行,而不是整个文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.