Search code examples
pythonvariablestxt

Setting Variable to readlines() index


I am simply opening a .txt and trying to set the first line to the variable x. My print function works just fine, but when I set it to a variable, all hell breaks loose. Am I missing something?

My .txt

cat
dog
horse
brid

Code

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

Output

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

Solution

  • Try:

    txt = open('path', 'rt')
    lst = txt.readlines() 
    
    print(lst[0])