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

标签 matlab file recursion file-io directory

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

MATLAB 支持这种操作吗?

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

最佳答案

更新:鉴于这篇文章已经很老了,而且我在那段时间修改了这个实用程序很多供自己使用,我想我应该发布一个新版本。我的最新代码可以在 The MathWorks File Exchange 上找到: dirPlus.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');

关于matlab - 如何在MATLAB中获取特定目录下的所有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2652630/

相关文章:

matlab - Matlab中基于色彩图的光栅图

linux - Linux中的TCP转串口用于Matlab访问

python - 如何将nltk中的特征写入txt文件?

C++文件流

recursion - 您将如何在 Prolog 中编写程序以使用递归打印从 1 到 10 的数字?

python - 在 matlab 中稀疏核/相似矩阵

python - Python 中的 Matlab 内联函数

php - 取消设置 $this

javascript - 如何从函数更改对象的属性

java - 生成所有有效的括号