【问题标题】:List index out of range when trying to read in a txt file in Python尝试在 Python 中读取 txt 文件时列表索引超出范围
【发布时间】:2022-01-03 03:03:38
【问题描述】:

我想用 Python 读取一个 txt 文件。文本文件由 3 列组成,所有列都用“,”分隔。一列表示 ID,一列表示随机浮点数,一列表示分配的属性(solo,not solo,acc)。

我的目标是将“solo”和“acc”的值转换为“not solo”,然后计算变量 y。

要求用户输入一个 ID(数字)。然后我想将 txt 文件的行转换为列表并搜索剩余的值,例如用户输入: 45 --> 我想搜索分配的值,然后将其转换为 'not solo' 并计算 y。最后,我想打印单位'not solo'中的赋值以及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.")

【问题讨论】:

  • 你能安排你的缩进吗?
  • 检查你的循环:可能太多且变量难以跟踪:file_list、file_content、choosen_line

标签: python list text iteration


【解决方案1】:

当你这样做时:

fobj = open('test.txt', 'r')
file_content = fobj.readline()
fobj.close()

您只读取一行,而不是整个文件。

【讨论】:

  • 谢谢!请问:如何将所有行都读取为列表?
  • 尝试:'fobj.read()'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 2014-08-20
  • 2019-12-11
  • 2023-03-28
  • 1970-01-01
  • 2022-01-17
  • 2015-10-23
相关资源
最近更新 更多