How to loop through a folder?

I currently have 24 folders within a folder and I was wondering if it was possible to loop through the 24 folders and extract information from a subfolder within the 24 folders.

댓글 수: 1

Brando Miranda
Brando Miranda 2018년 3월 30일
great question. This is some of the trivialest things to do in a language and its incomprehensible how hard it is to do in matlab.

댓글을 달려면 로그인하십시오.

답변 (3개)

Image Analyst
Image Analyst 2014년 3월 11일

4 개 추천

See my attached demo where it recurses through a folder and all subfolders.

댓글 수: 13

N
N 2014년 6월 11일
hi I love your code. I do have a question with it. If I would like to save the fullFileName, so it doesn't get overwritten every time, how would i do it?
Make it a cell array
fullFileName{counter} = fullfile(thisFolder, baseFileNames(f).name);
counter = counter + 1;
N
N 2014년 6월 11일
If I do this, I get the error:
Cell contents assignment to a non-cell array object.
Image Analyst
Image Analyst 2014년 6월 11일
Worked fine for me. See attachment.
N
N 2014년 6월 14일
thanks it works for me now too !
Mor H
Mor H 2016년 7월 4일
Thanks a lot !
Arantza Dobbels
Arantza Dobbels 2016년 7월 6일
Hey guys! this is exactly the code that I need but for some reason when I try to run it, it says the number of folders is 1 and then says that there are no files in the subfolders. What am I doing wrong? Thanks!
Vanessa Machuca
Vanessa Machuca 2017년 6월 16일
편집: Vanessa Machuca 2017년 6월 16일
I'm facing the same issue as Arantza. :(
Image Analyst
Image Analyst 2017년 6월 16일
I made a newer one to use the new capabilities of dir() to use to recurse into subfolders. Try it. It's attached. Works for Release R2016b and later.
Brando Miranda
Brando Miranda 2017년 12월 20일
do you a non recursive version?
Image Analyst
Image Analyst 2017년 12월 20일
Not sure what you're looking for. The program itself is not recursive - it uses the standard capability of the built-in dir() function. What I meant by recursive is that it finds files in folder, and in subfolders of those folder, and in subfolders of those subfolders, etc. until you've reached the deepest level of the directory tree.
What kind of problem are you having with the program such that you wanted to ask that question?
Rik
Rik 2020년 12월 10일
You can use the ** option of dir. What did you try?
Yes, essentially it's
filePattern = sprintf('%s/**/*.*', topLevelFolder);
allFileInfo = dir(filePattern);
See my attached m-file for a full demo with tons of explanations.

댓글을 달려면 로그인하십시오.

Sean de Wolski
Sean de Wolski 2014년 3월 11일
편집: Sean de Wolski 2014년 3월 11일

0 개 추천

You can use the dir command to give you the names and then loop over them.
files = dir;
directoryNames = {files([files.isdir]).name};
directoryNames = directoryNames(~ismember(directoryNames,{'.','..'}))
Now run the for-loop over directoryNames and apply your analysis to each

댓글 수: 7

andrew
andrew 2014년 3월 11일
i'm just wondering how do you get the specific files within the folders of the directory names for example:
I need to get a csv file inside the directory of each directory name '\results\statistics*\.v2*' and print the filenames in a column
Loop over the directory and use a wildcard inside of dir to grab all of the csv files. Something like
dir([directory '\*.csv'])
andrew
andrew 2014년 3월 11일
편집: Walter Roberson 2014년 3월 11일
I used the following code and it says the file was not found:
for i=1:length(directoryNames)
folder=directoryNames{i};
filenames=dir([folder '\results\object statistics *.v2*'])
end
Note: fullfile() is better practice than concatenating file substrings.
And if you were to construct the specification as a variable you could then
ls(TheVariable)
to see if the files are found that way.
why does
directories_names_list = dir('noise*')
for expt_dir = directories_names_list.name
not work?
why does
directoryNames = {files([files.isdir]).name};
work? its really cryptic? are u using list comprehensions or what dark magic is going on there?
Stephen23
Stephen23 2018년 3월 30일
편집: Stephen23 2018년 3월 30일
@Brando Miranda: "list comprehensions" exist only in Python. They do not exist in MATLAB.
The syntax in both your comments uses comma-separated lists. Comma-separated lists are very simple:

댓글을 달려면 로그인하십시오.

manideep reddy
manideep reddy 2018년 4월 18일

0 개 추천

see my code below but make sure that the folder which we are looping through contains only flolders and not files.

 cd pwd ; ## Or any other working directory you want
X = ls  ;
disp(X) ;
for itr = 1:size(X)(1)
	string_1 = X(itr,:) ;
	string_2{itr} = deblank(string_1) ;  ## This deletes the trailing blank spaces 			
end
for itr = 1:size(X)(1)
	cd(string_2{itr})
	cd ../
	# DO SOMETHING #
end
  end

댓글 수: 2

Stephen23
Stephen23 2018년 4월 18일
편집: Stephen23 2018년 4월 18일
This code has several bugs and could be significantly improved:
  • Do NOT use cd. Using cd is slower than using absolute/relative filepaths, makes debugging more difficult, and changes which functions/scripts are accessible to MATLAB. It is NOT necessary to cd directories where datafiles are stored because all MATLAB filereading/writing functions accept relative/absolute paths. Basically cd should only be used interactively, and NOT used in code. See:
  • Do NOT use ls for parsing filenames. This operator is intended for displaying a list in the command window, but parsing its output char array is a waste of time. dir is what the MATLAB documentation recommends and shows in all examples that require reading multiple files from a folder, e.g.:
  • size(X)(1) is not valid MATLAB syntax, and will throw an error.
  • string_2 is not preallocated.
  • A loop is anyway not required for deblanking the filenames: simply use deblank(cellstr(X)).
Rather than following this buggy code, I recommend that other users follow the examples shown in the MATLAB help and wiki:
manideep reddy
manideep reddy 2018년 4월 20일
Thank you very much. I am actually not a computer science student. So, just answered the query without considering algorithm and complexity. Anyway, I will implement your suggestions/ recommendations in future. Thanks..!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 File Operations에 대해 자세히 알아보기

태그

질문:

2014년 3월 11일

댓글:

2020년 12월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by