1

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.

1
  • Could you not assign your split array to a variable and access that directly instead of recalling the split function each time? Commented Mar 30, 2013 at 2:23

4 Answers 4

3

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()
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! I did not know that about invoking read().
Actually, read() reads the entire file, not just one line. It's just that in this case it looks like there's only one line in the file.
1

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.

Comments

0

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.