[英]saving text files to .npy file
I have many text files in a directory with numerical extension(example: signal_data1.9995100000000001,signal_data1.99961
etc)我在一个带有数字扩展名的目录中有许多文本文件(例如:
signal_data1.9995100000000001,signal_data1.99961
等)
The content of the files are as given below文件内容如下
signal_data1.9995100000000001信号数据1.9995100000000001
-1.710951390504200198e+00
5.720409824754981720e-01
2.730176313110273423e+00
signal_data1.99961信号数据1.99961
-6.710951390504200198e+01
2.720409824754981720e-01
6.730176313110273423e+05
I just want to arrange the above files into a single .npy files as我只想将上述文件排列成一个 .npy 文件作为
-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.然而,它没有给出我想要的,如上所示。所以在这里我需要帮助。提前致谢。
Here is another way of achieving it: '''python import os这是实现它的另一种方法:'''python 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()
''' '''
You can use np.loadtxt()
and np.save()
:您可以使用
np.loadtxt()
和np.save()
:
a = np.array([np.loadtxt(f) for f in sorted(glob.glob('./signal_*'))])
np.save('data.npy', a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.