[英]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.