奇怪的“IndexError:列表索引超出范围”错误。蟒蛇

时间:2013-03-30 02:20:25

标签: python syntax-error

我有一个程序需要使用类似的东西:

file1=open("cliente\\config.ini","r")

print file1.read().split(",")

user=file1.read().split(",")[0]
passwd=file1.read().split(",")[1]
domain=file1.read().split(",")[2]
file1.close()

在文件中有3个字符串,以“,”(用户,通行证,域名)分隔。

这是输出:

['user', 'pass', 'domain']
Traceback (most recent call last):
  File "C:\Users\default.default-PC\proyectoseclipse\dnsrat\prueba.py", line 8, in <module>
    passwd=file1.read().split(",")[1]
IndexError: list index out of range

我正在列表中的0,1和2字符串,所以我没有拿一个不存在的字符串。

那么,为什么我有错误?

非常感谢。

4 个答案:

答案 0 :(得分:3)

您正在阅读文件的末尾。当您在不带参数的情况下调用read时,将读取整个文件的内容,并且指针将前进到文件的末尾。你想要的是read一次,并将内容保存在变量中。然后,从中访问索引:

file1 = open("cliente\\config.ini","r")

line1 = file1.read().split(",")

user = line1[0]
passwd = line1[1]
domain = line1[2]
file1.close()

答案 1 :(得分:1)

read()将返回文件中的内容。来自the docs

...which reads some quantity of data and returns it as a string.

如果再次拨打电话,则无法阅读。

答案 2 :(得分:0)

read()是一种从读缓冲区获取数据的方法。而且你不能多次从缓冲区获取数据。

答案 3 :(得分:0)

file1=open("cliente\\config.ini","r")

data = file1.read().split(",")

user=data[0]
passwd=data[1]
domain=data[2]
file1.close()

您的第一个file.read()行会在读取该行后将光标移动到文件末尾。其他file.read()将不会按预期再次读取该文件。相反,它将从光标的末尾读取,并返回空字符串。