How can I get a list of all directory names and / or all files in a specific directory in MATLAB?

There are two things I want to do:

  • Get a list of all the directory names in the directory and
  • Get a list of all file names in a directory

How to do it in MATLAB?

Now I am trying:

dirnames = dir(image_dir);

but this returns a list of objects, I think. size(dirnames)returns the number of attributes, and dirnames.namereturns the name of the first directory.

+3
source share
3 answers

DIR . , . , , , [] , {}.

, , :

dirInfo = dir(image_dir);            %# Get structure of directory information
isDir = [dirInfo.isdir];             %# A logical index the length of the 
                                     %#   structure array that is true for
                                     %#   structure elements that are
                                     %#   directories and false otherwise
dirNames = {dirInfo(isDir).name};    %# A cell array of directory names
fileNames = {dirInfo(~isDir).name};  %# A cell array of file names
+5

. , dirnames.name.

D = dir;

. , ,

isdirlist = find(vertcat(D.isdir));

cell2mat . , D.name, , . , .

nameslist = {D.name};
+2

Assuming "image_dir" is the name of the directory, the following code shows how to determine which elements are directories and which are files, and how their names are. Once you have achieved this, creating a list of directories only or just files is easy.

dirnames = dir(image_dir);
for(i = 1:length(dirnames))
   if(dirnames(i).isdir == true)
      % It a subdirectory
      % The name of the subdirectory can be accessed as dirnames(i).name
      % Note that both '.' and '..' are subdirectories of any directory and
      % should be ignored
   else
      % It a filename
      % The filename is dirnames(i).name
   end
end
0
source

Source: https://habr.com/ru/post/1789374/


All Articles