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
5
  • Share the content of your input file Commented Apr 12, 2015 at 16:54
  • 3.141592654 2.718281828 1.414213562 0.707106781 0.017453293 Commented Apr 12, 2015 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)? Commented Apr 12, 2015 at 17:03
  • 1
    Each number is on a separate line, but there are no blank lines Commented Apr 12, 2015 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. Commented Apr 12, 2015 at 18:10

6 Answers 6

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

Comments

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()

Comments

1

for line1 in exam_data_file:

should be this :

for line1 in exam_data :

you are referring to a wrong object

6 Comments

It would still work though. Iterating through the file object is actually the recommended way to read lines in Python.
@pzp but after readlines the pointer is at the end of the file
@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: There's no problem with trailing or leading whitespace (including newlines) when converting a string to a float or an int.
@pzp Thanks for notifying
|
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]

10 Comments

@Dan1: Could you copy paste the full traceback please?
Traceback (most recent call last): File "/Users/Aliber/Desktop/CSC_108/Python lab b/data3.py", line 4, in <module> line1 = float(line1) ValueError: invalid literal for float(): 3.141592654 2.718281828 1.414213562 0.707106781 0.017453293
@Dan1: See my edited post :) I will now write explanations of the changes I made
@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?
|
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!

Comments

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)

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.