2

I have a text file with numbers separated by spaces, such as:

-2 -3 4 -1 -2 1.5 -3

I tried to create an numpy array with the file elements using the following code:

root = tk.Tk()
root.withdraw()
A = np.array([])
arquivox = filedialog.askopenfilename()
# reading datafile
with open(arquivox, "r") as f:
    for termox in f:
        # specifying the separator
        termox = termox.split(' ')
        # converting the elements to float and generating the array
        A = np.append(A, float(termox[0]))
print(A)

However, I am only saving the first element of the file (-2). What am I doing wrong?

4
  • 1
    Well you're only appending the first element... termox[0]... Maybe you need something more like A = np.array([float(x) for x in termox]) Commented Oct 14, 2020 at 13:01
  • 1
    Here float(termox[0]) you only take the first element (0). Commented Oct 14, 2020 at 13:01
  • 1
    You have a list of values in termox, yet you're only float/appending the first item in that list. You know how to iterate over an iterable (you're doing it earlier with for termox in f). Commented Oct 14, 2020 at 13:02
  • Oh, the way I was doing it was like I was waiting for the data to be separated by 'enter'. Thanks guys! Commented Oct 14, 2020 at 13:10

1 Answer 1

4

Since you are reading into a numpy.array anyway, I'd suggest using numpy.loadtxt

import numpy as np
A = np.loadtxt(arquivox, 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.