MATLAB dir without '.' and '..'

大憨熊 提交于 2019-12-21 07:07:09

问题


the function dir returns an array like

.
..
Folder1
Folder2

and every time I have to get rid of the first 2 items, with methods like :

for i=1:numel(folders)
    foldername = folders(i).name;
    if foldername(1) == '.' % do nothing
            continue;
    end
    do_something(foldername)
end

and with nested loops it can result in a lot of repeated code.

So can I avoid these "folders" by an easier way?

Thanks for any help!

Edit:

Lately I have been dealing with this issue more simply, like this :

for i=3:numel(folders)
    do_something(folders(i).name)
end

simply disregarding the first two items.

BUT, pay attention to @Jubobs' answer. Be careful for folder names that start with a nasty character that have a smaller ASCII value than .. Then the second method will fail. Also, if it starts with a ., then the first method will fail :)

So either make sure you have nice folder names and use one of my simple solutions, or use @Jubobs' solution to make sure.


回答1:


TL; DR

Scroll to the bottom of my answer for a function that lists directory contents except . and ...

Detailed answer

The . and .. entries correspond to the current folder and the parent folder, respectively. In *nix shells, you can use commands like ls -lA to list everything but . and ... Sadly, MATLAB's dir doesn't offer this functionality.

However, all is not lost. The elements of the output struct array returned by the dir function are actually ordered in lexicographical order based on the name field. This means that, if your current MATLAB folder contains files/folders that start by any character of ASCII code point smaller than that of the full stop (46, in decimal), then . and .. willl not correspond to the first two elements of that struct array.

Here is an illustrative example: if your current MATLAB folder has the following structure (!hello and 'world being either files or folders),

.
├── !hello
└── 'world

then you get this

>> f = dir;
>> for k = 1 : length(f), disp(f(k).name), end
!hello
'world
.
..

Why are . and .. not the first two entries, here? Because both the exclamation point and the single quote have smaller code points (33 and 39, in decimal, resp.) than that of the full stop (46, in decimal).

I refer you to this ASCII table for an exhaustive list of the visible characters that have an ASCII code point smaller than that of the full stop; note that not all of them are necessarily legal filename characters, though.

A custom dir function that does not list . and ..

Right after invoking dir, you can always get rid of the two offending entries from the struct array before manipulating it. Moreover, for convenience, if you want to save yourself some mental overhead, you can always write a custom dir function that does what you want:

function listing = dir2(varargin)

if nargin == 0
    name = '.';
elseif nargin == 1
    name = varargin{1};
else
    error('Too many input arguments.')
end

listing = dir(name);

inds = [];
n    = 0;
k    = 1;

while n < 2 && k <= length(listing)
    if any(strcmp(listing(k).name, {'.', '..'}))
        inds(end + 1) = k;
        n = n + 1;
    end
    k = k + 1;
end

listing(inds) = [];

Test

Assuming the same directory structure as before, you get the following:

>> f = dir2;
>> for k = 1 : length(f), disp(f(k).name), end
!hello
'world



回答2:


A loop-less solution:

d=dir;
d=d(~ismember({d.name},{'.','..'}));



回答3:


If you're just using dir to get a list of files and and directories, you can use Matlab's ls function instead. On UNIX systems, this just returns the output of the shell's ls command, which may be faster than calling dir. The . and .. directories won't be displayed (unless your shell is set up to do so). Also, note that the behavior of this function is different between UNIX and Windows systems.

If you still want to use dir, and you test each file name explicitly, as in your example, it's a good idea to use strcmp (or one of its relations) instead of == to compare strings. The following would skip all hidden files and folder on UNIX systems:

listing = dir;
for i = 1:length(listing)
    if ~strcmp(listing(i).name(1),'.')
        % Do something
        ...
    end
end



回答4:


a similar solution from the one suggested by Tal is:

listing = dir(directoryname);
listing(1:2)=[];   % here you erase these . and .. items from listing

It has the advantage to use a very common trick in Matlab, but assumes that you know that the first two items of listing are . and .. (which you do in this case). Whereas the solution provided by Tal (which I did not try though) seems to find the . and .. items even if they are not placed at the first two positions within listing.

Hope that helps ;)




回答5:


You may also wanna exclude any other files besides removing dots

d = dir('/path/to/parent/folder')
d(1:2)=[]; % removing dots 
d = d([d.isdir])    % [d.isdir] returns a logical array of 1s representing folders and 0s for other entries



回答6:


Combining @jubobs and @Tal solutions:

function d = dir2(folderPath)
% DIR2 lists the files in folderPath ignoring the '.' and '..' paths.

if nargin<1; folderPath = '.'; elseif nargin == 1

d = dir(folderPath);
d = d(~ismember({d.name},{'.','..'}));

end



回答7:


I used: a = dir(folderPath);

Then used two short code that return struct:

my_isdir = a([a.isdir]) Get a struct which only has folder info

my_notdir = a(~[a.isdir]) Get a struct which only has non-folder info



来源:https://stackoverflow.com/questions/27337514/matlab-dir-without-and

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!