reading .txt and .hdf5 file typed from the same folder

1 次查看(过去 30 天)
I have a folder that contains data files of type .txt and .hdf5, I am using the follwoing code to read the text files from this folder
% Specify the folder where the files live.
myFolder = 'C:\Users\Windows 10 Pro\Desktop\JRO_Data';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.*');
theFiles = dir(filePattern);
theFiles = theFiles(~[theFiles.isdir]); %remove folders from list
numfiles = length(theFiles);
DATA = cell(numfiles,2);
fullnames = fullfile({theFiles.folder}, {theFiles.name});
DATA(:,1) = fullnames(:); %cell array where we store the names of the files and the desired data
how can I modify this to be able to read .hdf5 as well, I am aware that there is a matlab function for reading such type but I am not sure how I can implement it in my code.

回答(1 个)

Walter Roberson
Walter Roberson 2021-10-2
dataset_to_read = 'something_appropriate';
for K = 1 : numfiles
got_hdf = false; got_table = false;
thisfile = fullnames{K};
[~, ~, ext] = fileparts(thisfile);
if ismember(ext, {'.hdf5', '.h5'})
data = h5read(thisfile, dataset_to_read);
got_hdf = true;
elseif ismember(ext, {'.hdf4', '.h4'})
data = hdfread(thisfile, dataset_to_read);
got_hdf = true;
elseif ismember(ext, {'.csv', '.xls', '.xlsx'})
data = readtable(thisfile);
got_table = true;
elseif ismember(ext, '.xt')
data = something appropriate
end
end
  3 个评论
Walter Roberson
Walter Roberson 2021-10-4
theFiles = [dir(fullfile(myFolder,'*.txt'));dir(fullfile(myFolder,'*.hdf5'))];
Walter Roberson
Walter Roberson 2021-10-4
dataset_to_read should be the HDF5 dataset path, not the folder to read the data into. The HDF5 dataset path will look similar to a unix path, starting with / and with parts separated by /

请先登录,再进行评论。

产品


版本

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by