Reputation: 1941
I have a program that need to use something like that:
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()
In the file there is 3 strings separated by a "," (user,pass,domain).
This is the output:
['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
I am taking the 0, 1 and 2 strings in the list so I am not taking one that does not exist.
So, why I am having an error??
Thank you very much.
Upvotes: 1
Views: 4368
Reputation:
You're reading past the end of the file. When you invoke read
without arguments, the contents of the entire file are read and the pointer advances to the end of the file. What you want is to read
once, and save the contents in a variable. Then, access indices from that:
file1 = open("cliente\\config.ini","r")
line1 = file1.read().split(",")
user = line1[0]
passwd = line1[1]
domain = line1[2]
file1.close()
Upvotes: 3
Reputation: 2429
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.
Upvotes: 0
Reputation: 9394
read() is a methoe to get data from reading buffer. And you can't get data from buffer more than one time.
Upvotes: 0
Reputation: 3429
read()
will return what's in the file. From the docs:
...which reads some quantity of data and returns it as a string.
If you call it again there won't be anything left to read.
Upvotes: 1