2

I have an input file text containing following entries

6.56
4.64
5.75
5.59
6.32
6.54
7.20
5.33

how can I convert this to list looking like following

[6.56,4.64,5.75,5.59,6.32,6.54,7.20,5.33]

pls help me

naz
  • 437
  • 1
  • 5
  • 8
  • 2
    [What have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – Volatility Feb 27 '13 at 10:00
  • 1
    Duplicate of : http://stackoverflow.com/questions/3925614/how-do-you-read-a-file-into-a-list-in-python. Or at least close enough so that it gives you the solution :) – jlengrand Feb 27 '13 at 10:03

4 Answers4

1
with open('filename.txt', 'r') as f:
    numbers = [float(x.strip()) for x in f]
mensi
  • 9,580
  • 2
  • 34
  • 43
  • 2
    You don't need the `strip()` - `float()` automatically does that. – Volatility Feb 27 '13 at 10:05
  • 1
    with open('filename.txt') as f: numbers = map(float, f) – Vladimir Feb 27 '13 at 10:06
  • @MarkusMeskanen -- did you try? – root Feb 27 '13 at 10:07
  • @Root Ye, it only gave me string `"6.56\n"` (and rest of the numbers obviously) –  Feb 27 '13 at 10:07
  • @Volatility Uuupsie, sorry I read your first comment wrong :D I thought you said that both `strip()` and `float()` are useless since reading from file automatically does it. My bad, should've focused harder :P –  Feb 27 '13 at 10:12
1

You could directly read it from the file by readlines (assuming one value on each line) and convert it to float.

values = open('filename.txt', 'rb').readlines()

values = [float(value.strip()) for value in values]
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
0

Say you have those values in a file named values.txt, you could try the following:

values = []
with open('values.txt', 'r') as f:
    values = [line.strip() for line in f]
Frankline
  • 40,277
  • 8
  • 44
  • 75
0
[ float(i) for i in open('your_file','r').read().split('\n') if i ]
Zulu
  • 8,765
  • 9
  • 49
  • 56