T
T
Timebird2016-07-25 22:03:12
Python
Timebird, 2016-07-25 22:03:12

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)

It works, but I don't know how to add it to the list.
(probs is from the word "probabilities", float numbers are probabilities. :))
I also tried this:
prob_list = []
probs = open('textfile.txt', 'r')
for line in probs:
  prob_list.append(line)
print('\nprob_list\n', prob_list)

Gives something like: [0.002703125\n, 0.002375\n, 0.001078125\n, 0.001796875\n, ...], but in the list.
The question is: how to write to the list in the first case and / or remove the line break characters in the second?
Thanks in advance).

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
AtomKrieg, 2016-07-25
@Timebird

prob_list = []
probs = open('textfile.txt', 'r')
for line in probs:
  prob_list.append(float(line))
print('\nprob_list\n', prob_list)

A
abcd0x00, 2016-07-26
@abcd0x00

[[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]
>>>

S
sim3x, 2016-07-25
@sim3x

prob_list = []
with open('textfile.txt', 'r') as probs:
   for line in probs:
      prob_list.append(float(line.strip()))
print('\nprob_list\n', prob_list)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question