python中的列表和文件

Max*_*rai 1 python file list

我正在使用readlinespython中的方法来获取所有数据行的列表.现在我不想从该列表中访问一些索引:

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

怎么了?

Tim*_*ker 5

我想你的意思是(如果你的目标是打印列表的第二个元素):

 print data[1]
Run Code Online (Sandbox Code Playgroud)

data.index(value)返回列表位置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
Run Code Online (Sandbox Code Playgroud)

  • 如果目标是在输入文件中打印第一行,请使用`print data [0]` (2认同)