将变量设置为 readlines() 索引

Setting Variable to readlines() index

我只是打开一个 .txt 并尝试将第一行设置为变量 x。我的打印功能工作得很好,但是当我将它设置为一个变量时,一切都乱套了。我错过了什么吗?

我的.txt

cat
dog
horse
brid

代码

txt = open('C:/Users/z/OneDrive/Desktop/New_Text_Doc.txt', 'r')
print(txt.readlines(0)[0])
x = txt.readlines(0)[0]

输出

Traceback (most recent call last):
  File "D:/KivyPractice/practice.py", line 4, in <module>
    x = txt.readlines(0)[0]
IndexError: list index out of range
cat

readlines 读取所有行。当你第二次调用 readlines 时,文件已经被读取,还有 0 行要读。 readline 读取一行。您可以先将该行读入变量,然后打印它。

txt_file = open('C:/Users/z/OneDrive/Desktop/New_Text_Doc.txt')
x = txt_file.readline()
print(x)

还有其他方法可以解决这个问题。最好的方法取决于你下一步想做什么。

尝试:

txt = open('path', 'rt')
lst = txt.readlines() 

print(lst[0])
with open("file.txt", "r") as f:
    lines = f.readlines()

x = lines[0]