0

I have a problem with the following code:

inputf = open('test.dat', 'r') lines = inputf.readlines() rico_clus_e = [] for line in lines: line.split() print line if (line[0] != '#'): rico_clus_e.append(float(line[4])) inputf.close() 

My test.dat file is:

# specn rico_all rico_all_e rico_clus rico_clus_e rico_farclust rico_far_e extin a119 1.07038692 0.11109547 0.61473431 0.15063627 0.32590239 0.14777812 0.207 

And this gives the following output in my terminal:

# specn rico_all rico_all_e rico_clus rico_clus_e rico_farclust rico_far_e extin a119 1.07038692 0.11109547 0.61473431 0.15063627 0.32590239 0.14777812 0.207 Traceback (most recent call last): File "test.py", line 8, in <module> rico_clus_e.append(float(line[4])) ValueError: could not convert string to float: 

I'm quite confused by this. It had nothing to do with spaces, I checked them all. And if you change 4 by 1, 2 or 3 this works, so it must have something to do with the test.dat file, but I can't seem to figure out how. I'm using python 2.7.3.

2
  • The representation (hint: repr()) of the element is...? Commented Jun 3, 2013 at 20:44
  • The representation is ' ' Commented Jun 3, 2013 at 20:52

1 Answer 1

1

line.split() on its own does nothing to line. You must store the result of the method call and use that instead.

Sign up to request clarification or add additional context in comments.

3 Comments

But why does it work for the other values? Changing 4 to 3, 2 or 1 does work... For number 3, the representation is '9', for element 2 it's '1'
That's because line[3] is '9', and line[2] is '1'. And line[0] is 'a'.
Okay, I understand your response now. It thought that '9' was something internal, but it just refers to the string. line = line.split() is the thing that did the trick. Thx!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.