无法读取行文本文件 python

Cant read lines text file python

我一直在使用python读写文本文件,变量之间用行分隔。我试图找到特定文件中有多少行并读取特定行上的内容,但似乎行数为 0,即使当我打印文件时它会给我正确的输出。我的代码如下:

import random
HUBCop = open("HUBCOUNT.txt","r+")
HUBCount = int(HUBCop.read())
HUBCop.close()
HUBNUM = str(input("Hub number: "))

if (HUBNUM == "new"):
    newHubOp=open("Hub " + (HUBCount + 1) +".txt", "w+")
    HUBNUM = str(HUBCount+1)
    HUBCop = open("HUBCOUNT.txt","w+")
    HUBCop.write(str(HUBCount + 1))
    output1 = input("Output 1: ")
    output2 = input("Output 2: ")
    newHubOp.write(output1 + "\n" + output2 + "1")
    newHubOp.close()
    TimesRun = 1
else:
    HubOp = open("Hub " + HUBNUM + ".txt","r+")
    HubOp.seek(0)
    HubLines = HubOp.readlines()
    HubOp.seek(0)
    print(str(len(HubLines)))
    print (HubLines[1])

Hub 文件 1.txt 包含以下内容:

true
false
1

然而,当我 运行 代码时,它给我这个输出:

0
Traceback (most recent call last):
File "/home/pi/Desktop/NN.py", line 23, in <module>
print (HubLines[1])
IndexError: list index out of range

请注意,我是 python 的新手,我正在使用 raspberry pi 3 和 python 3.6

感谢任何帮助,提前致谢

File.readlines() returns 行列表 所以你读到的那一行应该在:

HubLines[0]

或者只尝试:

HubLines

当您尝试访问 HubLines[1] 时,它显示 超出范围 因为它不存在