问题
I have the code like this:
myFolder='C:\Users\abe7rt\Desktop\dat\1';
filePattern=fullfile(myFolder, '*.txt');
txtFiles=dir(filePattern);
Now, dat is a folder that contains "1,2,3" folders and each one of these folders contains 20 TXT files. The previous code is able to get the txt files from 1 folder. Now my question is: is there a way to loop over all the directories?
回答1:
yes there is :)
A very nice function is this one:
by gnovice: getAllFiles
You can use it like this:
fileList = getAllFiles('D:\dic');
Then you just have to get rid of non-txt-files, e.g. by checking the extension within a loop!
回答2:
Yet another possibility, using the apache commons library that comes with MATLAB:
function fileNames = findAllFiles(directory, wildcardPattern)
import org.apache.commons.io.filefilter.*;
import org.apache.commons.io.FileUtils;
import java.io.File;
files = FileUtils.listFiles( File(directory),...
WildcardFileFilter(wildcardPattern),...
FileFilterUtils.trueFileFilter());
fileNames = cellfun(@(f) char(f.getCanonicalPath()),...
cell(files.toArray()),...
'uniformOutput', false);
end
Use e.g. as:
files = findAllFiles('C:\Users\abe7rt\Desktop\dat', '*.txt')
If you'd like to also apply a pattern on the directory-names in which the search should descend, you can simply replace the FileFilterUtils.trueFileFilter() with another WildcardFileFilter.
回答3:
Well you could do something like
for k=1:3
myFolder{k}=['C:\Users\abe7rt\Desktop\dat\' num2str(k)];
filePattern{k}=fullfile(myFolder{k}, '*.txt');
txtFiles{k}=dir(filePattern{k});
end
You can obviously pre-allocate the sizes of the arrays / cell arrays if performance/memory is an issue.
回答4:
You can use the recursive version of Matlab's function fileattrib, and then select the txt files with regexp. This solution works for any number of folders and any level of nesting.
[success,message,messageid] = fileattrib('C:\Users\abe7rt\Desktop\dat\*');
[names{1:numel(message)}] = deal(message.Name);
names_txt = names(~cellfun(@isempty, regexp(names,'\.txt$')));
The cell array names_txt contains the full names of all txt files. So names_txt{n} is a string with the full name of the n-th file.
Make sure you add the final \* to the root path.
来源:https://stackoverflow.com/questions/19024707/loop-over-folders