1

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

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

4 回答 4

3

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

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

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

user = line1[0]
passwd = line1[1]
domain = line1[2]
file1.close()
于 2013-03-30T02:23:48.123 回答
1

read()将返回文件中的内容。从文档

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

如果您再次调用它,将没有任何内容可供阅读。

于 2013-03-30T02:25:13.013 回答
0

read() is a methoe to get data from reading buffer. And you can't get data from buffer more than one time.

于 2013-03-30T02:26:27.347 回答
0
file1=open("cliente\\config.ini","r")

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

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

Your first file.read() line will move the cursor to the end of the file after reading the line. Other file.read() won't read the file again as you expected. Instead it will read from the end of the cursor and that will return empty string.

于 2013-03-30T02:28:49.393 回答