How to use for loop to read one file in multiple folders?

6 ビュー (過去 30 日間)
scully2014
scully2014 2018 年 10 月 7 日
コメント済み: Image Analyst 2018 年 10 月 7 日
I currently have a folder with 365 subfolders in it. Named Day_1, Day_2,....Day365. In each subfolder, there is a file named temp.txt. I want to read this file and extract data from all the subfolders. I can't figure out how to successfully do this with a loop. Any suggestions?

回答 (2 件)

Image Analyst
Image Analyst 2018 年 10 月 7 日
Use dir(). See attached example.
  1 件のコメント
Image Analyst
Image Analyst 2018 年 10 月 7 日
You haven't arrived at a solution yet? Alright, here is a simple example:
% Get a list of all files named temp.txt
% in the current folder or folders below it.
files = dir('**/temp.txt') % R2016b or later only
for k = 1 : length(files)
% Get the filename.
fullFileName = fullfile(files(k).folder, files(k).name)
thisData = importdata(fullFileName); % Read it in with some function.
% Now do something with thisData. Analyze it.
end

サインインしてコメントする。


Stephen23
Stephen23 2018 年 10 月 7 日
編集済み: Stephen23 2018 年 10 月 7 日
This should get you started:
D = 'directory where the subfolders are stored';
C = cell(1,365);
for k = 1:365
F = sprintf('Day_%d',k);
C{k} = csvread(fullfile(D,F,'temp.txt'));
end
Change csvread to an appropriate function that reads your text file. Read more:

カテゴリ

Help Center および File ExchangeSearch Path についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by