IndexError:列表索引超出范围

时间:2016-03-11 10:08:28

标签: python

enter image description here

我正在尝试运行以下脚本,

read_file = open ("test.txt", "r" )
line_content={}
file_content = read_file.read()
read_file.close()
line_list = file_content.split('\n')
for line in line_list:
    line_content = line.split()
    print(line_content[0])

但在输出后显示错误

  

Traceback(最近一次调用最后一次):文件“file_to_matrix.py”,第8行,   在       print(line_content [0])IndexError:列表索引超出范围

2 个答案:

答案 0 :(得分:0)

这只是意味着line_content没有元素[0],因此列表为空。

该文件很可能有一个新行\n,因此拆分它会产生一个空列表,该列表没有[0]个元素

答案 1 :(得分:0)

解决此问题的一种简单方法是在文件名后指定目录路径。

示例:python file_to_matrix.py Dropbox/PhD/python/code/

这将解决索引超出范围的错误。