0

I haven't found a solution so far and I tried so many things. Hope some of you guys can help me. I am using Python.

I have a .txt file with values like: 9,5,7,6,4

And I want to read this file as an array with float values, so it should look like:

array([9.0, 5.0, 7.0, 6.0, 4.0], dtype=float32)

The only thing I found so far is looks like:

array(['9,5,7,6,4),dtype='<U9']) 

and is a string and not a float.

Thanks for helping!

2
  • Does this answer your question? Reading floats from file with python Commented Dec 10, 2020 at 22:43
  • read it as text using open(), read(); split in with split(",") and you get list ["9", "5" , "7", "6", "4"] - and use for-loop with float() to convert every element on list to float value. Commented Dec 11, 2020 at 0:01

1 Answer 1

0

Read it as text

text = open(filename).read()  # "9,5,7,6,4"

split to list of strings

data = text.split(',')  # ["9", "5" , "7", "6", "4"]

convert every string to float

values = [float(x) for x in data]  # [9.0, 5.0, 7.0, 6.0, 4.0]

Example code

#text = open(filename).read()
text = '9,5,7,6,4'

data = text.split(',')
values = [float(x) for x in data]

print(values)
# [9.0, 5.0, 7.0, 6.0, 4.0]

EDIT:

If you use array() then probably you use numpy so you should see numpy.loadtxt which should do what you want - you have to only use delimiter=','

Sign up to request clarification or add additional context in comments.

Comments

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.