Max Frai
Max Frai

Reputation: 64276

List and files in python

I'm using readlines method from python to get list of all data lines. Now I wan't to access some index from that list:

file = open('article.txt', 'r')
data = file.readlines()
print data.index(1)
Error: data isn't a list

What's wrong?

Upvotes: 1

Views: 224

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

I think you mean (if your goal is to print the second element of the list):

 print data[1]

data.index(value) returns the list position of value:

>>> data = ["a","b","c"]
>>> data[1]          # Which is the second element of data?
b
>>> data.index("a")  # Which is the position of the element "a"?
0
>>> data.index("d")  # Which is the position of the element "d"? --> not in list!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list

Upvotes: 5

Jochen Ritzel
Jochen Ritzel

Reputation: 107608

Sounds like you mean print data[1] not print data.index(1). See the tutorial

Upvotes: 1

Related Questions