如何在MATLAB中获取特定目录下的所有文件?

问题描述 投票:93回答:8

我需要在D:\dic下获取所有这些文件并循环遍历它们以进一步单独处理。

MATLAB是否支持这种操作?

它可以在其他脚本中完成,如PHP,Python ......

matlab file recursion file-io directory
8个回答
127
投票

更新:鉴于这篇文章相当陈旧,我在这段时间内为自己的用途修改了这个实用程序,我想我应该发布一个新版本。我的最新代码可以在The MathWorks File ExchangedirPlus.m上找到。您也可以从GitHub获取源代码。

我做了很多改进。它现在为您提供了前置完整路径或仅返回文件名(从DoresoomOz Radiano合并)的选项,并将正则表达式模式应用于文件名(从Peter D合并)。此外,我添加了将验证功能应用于每个文件的功能,允许您根据除其名称之外的条件(即文件大小,内容,创建日期等)选择它们。


注意:在较新版本的MATLAB(R2016b及更高版本)中,dir函数具有递归搜索功能!因此,您可以执行此操作以获取当前文件夹的所有子文件夹中的所有*.m文件的列表:

dirData = dir('**/*.m');

旧代码:(后代)

这是一个以递归方式搜索给定目录的所有子目录的函数,收集它找到的所有文件名的列表:

function fileList = getAllFiles(dirName)

  dirData = dir(dirName);      %# Get the data for the current directory
  dirIndex = [dirData.isdir];  %# Find the index for directories
  fileList = {dirData(~dirIndex).name}';  %'# Get a list of the files
  if ~isempty(fileList)
    fileList = cellfun(@(x) fullfile(dirName,x),...  %# Prepend path to files
                       fileList,'UniformOutput',false);
  end
  subDirs = {dirData(dirIndex).name};  %# Get a list of the subdirectories
  validIndex = ~ismember(subDirs,{'.','..'});  %# Find index of subdirectories
                                               %#   that are not '.' or '..'
  for iDir = find(validIndex)                  %# Loop over valid subdirectories
    nextDir = fullfile(dirName,subDirs{iDir});    %# Get the subdirectory path
    fileList = [fileList; getAllFiles(nextDir)];  %# Recursively call getAllFiles
  end

end

在MATLAB路径的某处保存上述函数后,可以通过以下方式调用它:

fileList = getAllFiles('D:\dic');

25
投票

您正在寻找dir来返回目录内容。

要循环结果,您只需执行以下操作:

dirlist = dir('.');
for i = 1:length(dirlist)
    dirlist(i)
end

这应该给你以下列格式的输出,例如:

name: 'my_file'
date: '01-Jan-2010 12:00:00'
bytes: 56
isdir: 0
datenum: []

13
投票

我使用this great answer中提到的代码并将其扩展为支持我需要的2个额外参数。参数是要过滤的文件扩展名和一个标志,指示是否连接文件名的完整路径。

我希望它足够清楚,有人会发现它有益。

function fileList = getAllFiles(dirName, fileExtension, appendFullPath)

  dirData = dir([dirName '/' fileExtension]);      %# Get the data for the current directory
  dirWithSubFolders = dir(dirName);
  dirIndex = [dirWithSubFolders.isdir];  %# Find the index for directories
  fileList = {dirData.name}';  %'# Get a list of the files
  if ~isempty(fileList)
    if appendFullPath
      fileList = cellfun(@(x) fullfile(dirName,x),...  %# Prepend path to files
                       fileList,'UniformOutput',false);
    end
  end
  subDirs = {dirWithSubFolders(dirIndex).name};  %# Get a list of the subdirectories
  validIndex = ~ismember(subDirs,{'.','..'});  %# Find index of subdirectories
                                               %#   that are not '.' or '..'
  for iDir = find(validIndex)                  %# Loop over valid subdirectories
    nextDir = fullfile(dirName,subDirs{iDir});    %# Get the subdirectory path
    fileList = [fileList; getAllFiles(nextDir, fileExtension, appendFullPath)];  %# Recursively call getAllFiles
  end

end

运行代码的示例:

fileList = getAllFiles(dirName, '*.xml', 0); %#0 is false obviously

8
投票

您可以使用regexp或strcmp来消除...或者如果您只想要目录中的文件而不是文件夹,则可以使用isdir字段。

list=dir(pwd);  %get info of files/folders in current directory
isfile=~[list.isdir]; %determine index of files vs folders
filenames={list(isfile).name}; %create cell array of file names

或结合最后两行:

filenames={list(~[list.isdir]).name};

对于目录中的文件夹列表,不包括。和..

dirnames={list([list.isdir]).name};
dirnames=dirnames(~(strcmp('.',dirnames)|strcmp('..',dirnames)));

从这一点开始,您应该能够在嵌套的for循环中抛出代码,并继续搜索每个子文件夹,直到您的dirnames为每个子目录返回一个空单元格。


7
投票

这个答案并没有直接回答这个问题,但可能是一个很好的解决方案。

我赞成了gnovice的解决方案,但想提供另一种解决方案:使用操作系统的系统相关命令:

tic
asdfList = getAllFiles('../TIMIT_FULL/train');
toc
% Elapsed time is 19.066170 seconds.

tic
[status,cmdout] = system('find ../TIMIT_FULL/train/ -iname "*.wav"');
C = strsplit(strtrim(cmdout));
toc
% Elapsed time is 0.603163 seconds.

正:

  • 非常快(在我的情况下,在Linux上的18000个文件的数据库)。
  • 您可以使用经过良好测试的解决
  • 您不需要学习或重新发明新语法来选择即*.wav文件。

负:

  • 您不是系统独立的。
  • 您依赖于可能难以解析的单个字符串。

3
投票

我不知道单功能方法,但你可以使用genpath来递归子目录列表。此列表以分号分隔的目录字符串形式返回,因此您必须使用strread将其分隔,即

dirlist = strread(genpath('/path/of/directory'),'%s','delimiter',';')

如果您不想包含给定目录,请删除dirlist的第一个条目,即dirlist(1)=[];,因为它始终是第一个条目。

然后使用循环dir获取每个目录中的文件列表。

filenamelist=[];
for d=1:length(dirlist)
    % keep only filenames
    filelist=dir(dirlist{d});
    filelist={filelist.name};

    % remove '.' and '..' entries
    filelist([strmatch('.',filelist,'exact');strmatch('..',filelist,'exact'))=[];
    % or to ignore all hidden files, use filelist(strmatch('.',filelist))=[];

    % prepend directory name to each filename entry, separated by filesep*
    for f=1:length(filelist)
        filelist{f}=[dirlist{d} filesep filelist{f}];
    end

    filenamelist=[filenamelist filelist];
end

filesep返回运行MATLAB的平台的目录分隔符。

这将为您提供单元格数组filename列表中包含完整路径的文件名列表。我知道,这不是最好的解决方案。


1
投票

这是一个方便的函数,用于获取文件名,在根文件夹中使用指定的格式(通常为.mat)!

    function filenames = getFilenames(rootDir, format)
        % Get filenames with specified `format` in given `foler` 
        %
        % Parameters
        % ----------
        % - rootDir: char vector
        %   Target folder
        % - format: char vector = 'mat'
        %   File foramt

        % default values
        if ~exist('format', 'var')
            format = 'mat';
        end

        format = ['*.', format];
        filenames = dir(fullfile(rootDir, format));
        filenames = arrayfun(...
            @(x) fullfile(x.folder, x.name), ...
            filenames, ...
            'UniformOutput', false ...
        );
    end

在您的情况下,您可以使用以下代码段:)

filenames = getFilenames('D:/dic/**');
for i = 1:numel(filenames)
    filename = filenames{i};
    % do your job!
end

0
投票

通过很少的修改但几乎相似的方法来获取每个子文件夹的完整文件路径

dataFolderPath = 'UCR_TS_Archive_2015/';

dirData = dir(dataFolderPath);      %# Get the data for the current directory
dirIndex = [dirData.isdir];  %# Find the index for directories
fileList = {dirData(~dirIndex).name}';  %'# Get a list of the files
if ~isempty(fileList)
    fileList = cellfun(@(x) fullfile(dataFolderPath,x),...  %# Prepend path to files
        fileList,'UniformOutput',false);
end
subDirs = {dirData(dirIndex).name};  %# Get a list of the subdirectories
validIndex = ~ismember(subDirs,{'.','..'});  %# Find index of subdirectories
%#   that are not '.' or '..'
for iDir = find(validIndex)                  %# Loop over valid subdirectories
    nextDir = fullfile(dataFolderPath,subDirs{iDir});    %# Get the subdirectory path
    getAllFiles = dir(nextDir);
    for k = 1:1:size(getAllFiles,1)
        validFileIndex = ~ismember(getAllFiles(k,1).name,{'.','..'});
        if(validFileIndex)
            filePathComplete = fullfile(nextDir,getAllFiles(k,1).name);
            fprintf('The Complete File Path: %s\n', filePathComplete);
        end
    end
end  
© www.soinside.com 2019 - 2024. All rights reserved.