Home > front end >  saving text files to .npy file
saving text files to .npy file

Time:10-28

I have many text files in a directory with numerical extension(example: signal_data1.9995100000000001,signal_data1.99961 etc)

The content of the files are as given below

signal_data1.9995100000000001

-1.710951390504200198e 00
 5.720409824754981720e-01
 2.730176313110273423e 00

signal_data1.99961

-6.710951390504200198e 01
 2.720409824754981720e-01
 6.730176313110273423e 05

I just want to arrange the above files into a single .npy files as

-1.710951390504200198e 00,5.720409824754981720e-01, 2.730176313110273423e 00
-6.710951390504200198e 01,2.720409824754981720e-01, 6.730176313110273423e 05

So same procedure i want to implement for many files of a directory.

I tried the loop as follows:

import numpy as np
import glob
for file in glob.glob(./signal_*):
    np.savez('data', file)

However it doesnot give what i want as depicted above.So here i need help.Thanks in advance.

CodePudding user response:

Here is another way of achieving it:

import os 

dirPath = './data/' # folder where you store your data

with os.scandir(dirPath) as entries:
    output = ""
    for entry in entries: # read each file in your folder
        dataFile = open(dirPath   entry.name, "r")
        dataLines = dataFile.readlines()
        dataFile.close()
        for line in dataLines:
            output  = line.strip()   " " # clear all unnecessary characters & append
        output  = '\n' # after each file break line
    writeFile = open("a.npy", "w") # save it
    writeFile.write(output)
    writeFile.close()

CodePudding user response:

You can use np.loadtxt() and np.save():

a = np.array([np.loadtxt(f) for f in sorted(glob.glob('./signal_*'))])
np.save('data.npy', a)
  • Related