read result.txt files with same file name is subfolders
조회 수: 2 (최근 30일)
이전 댓글 표시
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.
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!
댓글 수: 0
채택된 답변
Subhadeep Koley
2019년 11월 5일
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!
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 File Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!