0

It is a txt file with 99255 numbers in a row.

This is some example of txt file :

    -0.640157 
    -0.556037 
    -0.692255 
    -0.553077 
    -0.932098 
    -0.749993 
    -0.713643 
    -0.838611 
    -0.734945 
    -0.837929 
    .
    .
    .

I want to load these numbers in float type and assign them in np.array form.

Please help. Thank you.

2 Answers 2

1

You can use numpy directly

import numpy as np
filename = "/path/to/file"
array = np.loadtxt(filename, np.float)
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your comment. I created an ex.txt file consisting of 1 2 3 4 and tried to substitute your code. But when I try to print to see if it was assigned successfully, I get a strange result like [8.035657e-09 5.517073e-31]. May I ask why this is happening?
I am sorry for the mistake, the function should be loadtxt not fromfile. I have edited it alreay
@InsungLee If the answer helped, please consider accepting it
0

Read line by line and convert to float each element. Append them in a list, then convert the list.

import numpy as np

with open(filename, 'r') as f:
    line = f.readLine().strip('\n')
    l = []
    while line:
        l.append(float(line))
        line = f.readLine().strip('\n')

np.asarray(l)

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.