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

2

4 Answers 4

1
with open('filename.txt', 'r') as f:
    numbers = [float(x.strip()) for x in f]
Sign up to request clarification or add additional context in comments.

5 Comments

You don't need the strip() - float() automatically does that.
with open('filename.txt') as f: numbers = map(float, f)
@MarkusMeskanen -- did you try?
@Root Ye, it only gave me string "6.56\n" (and rest of the numbers obviously)
@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
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]

Comments

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]

Comments

0
[ float(i) for i in open('your_file','r').read().split('\n') if i ]

2 Comments

Wouldn't that leave an open file around?
Not sure... but doesn't appear in lsof.

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.