简体   繁体   中英

python list of floats from text file

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

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

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

for line1 in exam_data_file:

should be this :

for line1 in exam_data :

you are referring to a wrong object

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'ssplit 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]

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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM