![](/img/trans.png)
[英]Splitting text file to separate files, and saving substrings in filenames; Python
[英]saving text files to .npy file
我在一個帶有數字擴展名的目錄中有許多文本文件(例如: signal_data1.9995100000000001,signal_data1.99961
等)
文件內容如下
信號數據1.9995100000000001
-1.710951390504200198e+00
5.720409824754981720e-01
2.730176313110273423e+00
信號數據1.99961
-6.710951390504200198e+01
2.720409824754981720e-01
6.730176313110273423e+05
我只想將上述文件排列成一個 .npy 文件作為
-1.710951390504200198e+00,5.720409824754981720e-01, 2.730176313110273423e+00
-6.710951390504200198e+01,2.720409824754981720e-01, 6.730176313110273423e+05
所以我想為一個目錄的許多文件實現同樣的過程。
我嘗試了如下循環:
import numpy as np
import glob
for file in glob.glob(./signal_*):
np.savez('data', file)
然而,它沒有給出我想要的,如上所示。所以在這里我需要幫助。提前致謝。
這是實現它的另一種方法:'''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()
'''
您可以使用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.