read result.txt files with same file name is subfolders

2 vues (au cours des 30 derniers jours)
Henning Eimstad
Henning Eimstad le 2 Nov 2019
Im using a software to run an analysis with a variable (in this case 12 different several wind speeds). I have a main folder with a subfolder for each wind speed with alot of files. However I am only interested in reading the results.tda file in each subfolder (they all have the same name). I have managed to read all the subfolders, creating the D_sub which gives a 1x12 struct with each file and corresponding folder as seen in the image below. In this example Ive used the txt file for testing but I also want to use the results.tda files.
subfold.png
However, I am only able to get the last result.txt file in the workspace.
I am currently using the following code to go through the folders and find the files, but "content" only gives me the data for the last run (Wind_9).
Goal: to get e.g. result1 for Wind1, result5 for Wind5 etc etc and to be able to extract the data I want from each result file.
Main = 'C:MainFolder';
Sub = dir(fullfile(Main,'*'));
Sub = Sub(3:end); % Eliminate "." and ".."
N = setdiff({Sub([Sub.isdir]).name},{'.','..'}); % list of subfolders of Main.
for i = 1 : numel(N)
D_sub(i) = dir( fullfile( Main, Sub(i).name, 'results.txt' )) ;
nel = {D_sub(~[D_sub.isdir]).name};
for j = 1 : numel(nel)
inLocator = fullfile( Main, Sub(i).name, D_sub(j).name ) ;
content = fileread( inLocator ) ;
end
end
Thanks!

Réponse acceptée

Subhadeep Koley
Subhadeep Koley le 5 Nov 2019
Hi, you have defined content’as a single variable, therefore it is holding only the last value of the loop. If you want to want to save each loop data to a separate variable, the following code might help you.
Just declare content’as an empty cell array and access every cell of the variable content’using the indexing variable j in every loop.
Main = 'C:MainFolder';
Sub = dir(fullfile(Main,'*'));
Sub = Sub(3:end); % Eliminate "." and ".."
N = setdiff({Sub([Sub.isdir]).name},{'.','..'}); % list of subfolders of Main.
for i = 1 : numel(N)
D_sub(i) = dir( fullfile( Main, Sub(i).name, 'results.txt' )) ;
nel = {D_sub(~[D_sub.isdir]).name};
% Declare empty cell array content
content = {};
for j = 1 : numel(nel)
inLocator = fullfile( Main, Sub(i).name, D_sub(j).name ) ;
content{j} = fileread( inLocator ) ;
end
end
In this way your ‘Wind_1’ data will be in content(1), ‘Wind_2’ data will be in content(2), and so on…
Also, you might want to read why you should always use indexing instead of dynamically named variables here.
Hope this helps!

Plus de réponses (0)

Catégories

En savoir plus sur File Operations dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by