简体   繁体   中英

How to read space-separated data into a numpy array?

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?

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

import numpy as np
A = np.loadtxt(arquivox, delimiter=' ')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM