0

I am trying to create a list of floats from a text file with this code:

exam_data_file = open('exam_data.txt','r')
exam_data = exam_data_file.readlines()
exam_data1 = []

for line1 in exam_data_file:
    line1 = float(line1)
    exam_data1.append(line1)

 print(exam_data1)     

but the output is simply: []

Can someone please help?!

Now I get this error message regardless of the changes I make:

line1 = float(line1)


ValueError: invalid literal for float(): 3.141592654
2.718281828
1.414213562
0.707106781
0.017453293
abcd
  • 10,215
  • 15
  • 51
  • 85
Dan1
  • 11
  • 1
  • 3
  • Share the content of your input file – Akhil Thayyil Apr 12 '15 at 16:54
  • 3.141592654 2.718281828 1.414213562 0.707106781 0.017453293 – Dan1 Apr 12 '15 at 16:55
  • 1
    How is that content arranged in the input file? All on one line, separated by spaces? Each number on a separate line? If the latter, are there any lines in the file that *don't* contain a number (e.g., a blank line at the start or end)? – Mark Dickinson Apr 12 '15 at 17:03
  • 1
    Each number is on a separate line, but there are no blank lines – Dan1 Apr 12 '15 at 17:07
  • @Dan1, what did you change in your code to cause it to stop outputing `[]` and start raising the error? i'm pretty, pretty, pretty sure that you don't get this error message "regardless of the changes [you] make." that's a _crazy_ thing to say. – abcd Apr 12 '15 at 18:10

6 Answers6

2

Why don't use literal_eval n -(easier to use)

You can read and print a simple list or multi-dimensional lists simply with literal_eval

from ast import literal_eval

f=open("demofile.txt",'r')

for line in f:
    new_list = literal_eval(line)

print(new_list)
f.close()
2

https://stackoverflow.com/a/59717679/10151945 This answer is quit relevant. here an example that i have done with :

from ast import literal_eval
file=open("student_list.txt",'r')
for student in file:
    student_list_final = literal_eval(student)
print(student_list_final)
file.close()
1

for line1 in exam_data_file:

should be this :

for line1 in exam_data :

you are referring to a wrong object

Akhil Thayyil
  • 9,263
  • 6
  • 34
  • 48
  • It would still work though. Iterating through the file object is actually the recommended way to read lines in Python. – pzp Apr 12 '15 at 16:58
  • 2
    @pzp but *after* `readlines` the pointer is at the end of the file – jonrsharpe Apr 12 '15 at 17:00
  • 1
    @Akhil Thayyil's answer is still wrong though. ```readlines()``` does not strip whitespace (i.e. newlines), so there will still be an error when OP attempts to convert to floats. – pzp Apr 12 '15 at 17:10
  • @pzp: There's no problem with trailing or leading whitespace (including newlines) when converting a string to a float or an int. – Mark Dickinson Apr 12 '15 at 17:11
  • @pzp Thanks for notifying – Akhil Thayyil Apr 12 '15 at 17:13
  • @Akhil Thayyil : Whoops, you were right to begin with; I didn't realize that float ignores trailing whitespace. – pzp Apr 12 '15 at 17:14
0

There are actually two problems in your code:

  • The first problem is that you are actually reading the file two times. One time line 2 (exam_data_file.readlines()) and one second time line 5 while executing the for-loop. You can't read a file twice. For further information see this post.

  • The second problem is that line1 is currently a whole line in your file (in your case a chain of separate floats), and not a single float as you expected it to be. That's why you get the Invalid literal error. You have to split it into separate numbers in order to call float upon them. That's why you have to call the string's split method.

Try this instead:

exam_data_file = open('exam_data.txt','r')
exam_data1 = []

for line in exam_data_file:
    exam_data1.extend([float(i) for i in line.split()])

print(exam_data1) 

Output:

[3.141592654, 2.718281828, 1.414213562, 0.707106781, 0.017453293]
Community
  • 1
  • 1
aldeb
  • 6,588
  • 5
  • 25
  • 48
  • @Dan1: Could you copy paste the full traceback please? – aldeb Apr 12 '15 at 17:04
  • Traceback (most recent call last): File "/Users/Aliber/Desktop/CSC_108/Python lab b/data3.py", line 4, in line1 = float(line1) ValueError: invalid literal for float(): 3.141592654 2.718281828 1.414213562 0.707106781 0.017453293 – Dan1 Apr 12 '15 at 17:06
  • @Dan1: See my edited post :) I will now write explanations of the changes I made – aldeb Apr 12 '15 at 17:10
  • @Controll, i'm not following your reasoning. you say, "The second problem is that `line1` is currently a string . . ." but that alone is not a problem. strings can be cast as floats: e.g., `float('1.2')` returns `1.2`. can you rephrase? – abcd Apr 12 '15 at 17:22
  • @dbliss You are absolutely right. see my edited post :) – aldeb Apr 12 '15 at 17:23
  • @dbliss: But the traceback itself says all the information is in one single line. See the third comment on this post. – aldeb Apr 12 '15 at 17:49
  • i think that's a consequence of it being in a comment -- comments don't show new lines. – abcd Apr 12 '15 at 17:51
  • @dbliss: I understand. But that's not the point. The message "invalid literal for float(): .... " Means the whole literal quoted in the exception was passed as and argument to `float`" – aldeb Apr 12 '15 at 17:54
  • oh, totally agree. but that raises a new question. why does a single element in `readlines()` contain multiple lines? (as opposed to, as you say, "a whole line.") – abcd Apr 12 '15 at 17:58
  • 1
    Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/75063/discussion-between-controll-and-dbliss). – aldeb Apr 12 '15 at 18:00
0

You've made an error choosing the error to iterate over in the for loop.

for line1 in exam_data: # not the file!
    line1 = float(line1)
    exam_data1.append(line1)

This could be further improved with

exam_data = []
with open('exam_data.txt','r') as open_file:
    for line1 in open_file:
        line1 = float(line1)
        exam_data.append(line1)

print(exam_data)

The context handler (with syntax) will make sure you close the file after you have processed it!

Matt Davidson
  • 728
  • 4
  • 9
0

Since a file-like object is an iterable, you can just use map.

with open('exam_data.txt','r') as f:
    exam_data = map(float, f)
pzp
  • 6,249
  • 1
  • 26
  • 38