Answer the question
In order to leave comments, you need to log in
How to read data from a file and write it to a list?
There is a file with numbers of type float written in it. Each line has one number. It is necessary to count them from there, and then write them to the list. Tried like this:
probs_in_file = open("textfile.txt")
probs = probs_in_file.read()
probs_in_file.close()
print('\nprobs:\n', probs)
prob_list = []
probs = open('textfile.txt', 'r')
for line in probs:
prob_list.append(line)
print('\nprob_list\n', prob_list)
Answer the question
In order to leave comments, you need to log in
prob_list = []
probs = open('textfile.txt', 'r')
for line in probs:
prob_list.append(float(line))
print('\nprob_list\n', prob_list)
[[email protected] py]$ cat file.txt
1.5
2.6
3.123
4.56
[[email protected] py]$
>>> with open('file.txt') as fin:
... lst = list(map(float, fin))
...
>>> lst
[1.5, 2.6, 3.123, 4.56]
>>>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question