python - python中的列表和文件

标签 python list file

我正在使用 python 中的 readlines 方法来获取所有数据行的列表。现在我不想访问该列表中的某些索引:

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

怎么了?

最佳答案

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

 print data[1]

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

关于python - python中的列表和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4368812/

相关文章:

python - CodingBat 热身 2 Python Last2

Python 3.3 - 需要帮助使用 .txt 中的数据编写 .png 文件

python - 用于发布到 Google+ 的简单 Python 代码

python - xreadlines 和 for 循环文件之间的区别

jquery - jQuery声音通知有关新文件的内容

python - 查找错误: no codec search functions registered: can't find encoding

c# - ForEach 用于 Linq 中的列表列表

javascript - 让用户在巨大的可搜索列表中选择数据的常见方法

python - 根据类别对列表进行分组

Java从文件中读取数组