How to read all the files in a folder based on file name?
조회 수: 5 (최근 30일)
이전 댓글 표시
Dear MATLAB Experts,
I have hundreds of files in a folder and I need toread all the files using last 5 digits of file name.
RSS_SSMIS_FCDR_V07R00_F17_D20220701_S0134_E0326_R80783
Here problem is this information is random in each file S0134_E0326.
However R80783 is increasing for next file, as shown in image.
%% code for readin file is
clear;clc; close;
ncfile_1 = 'RSS_SSMIS_FCDR_V07R00_F17_D20220701_S0134_E0326_R80783.nc' ;
ncinfo(ncfile_1)
ncdisp(ncfile_1)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1676926/image.png)
댓글 수: 0
채택된 답변
Mathieu NOE
2024년 4월 23일
hello
you can do a for loop to load all your files
I am not sure what your issue is, but if it's how to make sure to load files according to the last 5 digits, you can check that dir combined with natsortfiles guarantees to load your files in ascending order , whatever the file name is before the 5 digits
natsortfiles is available on the Fex :
try it !
this is my result (I created the first 3 files of your list) - you can see the files are sorted out correctly
filename = 'RSS_SSMIS_FCDR_V07R00_F17_D20220701_S0134_E0326_R80783.nc'
filename_last5digits = 80783
filename = 'RSS_SSMIS_FCDR_V07R00_F17_D20220701_S0316_E0508_R80784.nc'
filename_last5digits = 80784
filename = 'RSS_SSMIS_FCDR_V07R00_F17_D20220701_S0458_E0650_R80785.nc'
filename_last5digits = 80785
fileDir = pwd; % current directory (or specify which one is the working directory)
S = dir(fullfile(fileDir,'*.nc')); % get list of data files in directory
S = natsortfiles(S); % sort file names into natural order , see :
%(https://fr.mathworks.com/matlabcentral/fileexchange/47434-natural-order-filename-sort)
N = numel(S);
for k = 1:N
filename = S(k).name % plot the file name in command window (on purpose)
filename_last5digits = str2double(extractBetween(filename,'_R','.nc')) % plot the file name last 5 digits in command window (on purpose)
% % Load in a few selected variables
% u = ncread(filename,'XXX');
end
댓글 수: 8
Mathieu NOE
2024년 4월 24일
ok, I see you managed the problem in your final code - good point !!
Glad we could help you and all the best for the future :)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!