首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在MATLAB中获取特定目录下的所有文件?

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

Stack Overflow用户
提问于 2010-04-16 19:49:15
回答 5查看 166.5K关注 0票数 102

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

MATLAB支持这种操作吗?

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

EN

回答 5

Stack Overflow用户

发布于 2010-04-16 21:41:25

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

要遍历结果,只需执行以下操作:

代码语言:javascript
复制
dirlist = dir('.');
for i = 1:length(dirlist)
    dirlist(i)
end

这将给出以下格式的输出,例如:

代码语言:javascript
复制
name: 'my_file'
date: '01-Jan-2010 12:00:00'
bytes: 56
isdir: 0
datenum: []
票数 25
EN

Stack Overflow用户

发布于 2014-10-19 17:19:17

我使用了this great answer中提到的代码,并对其进行了扩展,以支持我在本例中需要的两个附加参数。这些参数是要筛选的文件扩展名,以及指示是否将完整路径连接到文件名的标志。

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

代码语言:javascript
复制
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

运行代码的示例:

代码语言:javascript
复制
fileList = getAllFiles(dirName, '*.xml', 0); %#0 is false obviously
票数 14
EN

Stack Overflow用户

发布于 2010-04-16 22:59:25

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

代码语言:javascript
复制
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

或者将最后两行合并:

代码语言:javascript
复制
filenames={list(~[list.isdir]).name};

有关目录中不包括的文件夹的列表。然后..。

代码语言:javascript
复制
dirnames={list([list.isdir]).name};
dirnames=dirnames(~(strcmp('.',dirnames)|strcmp('..',dirnames)));

至此,您应该能够将代码抛入嵌套的for循环中,并继续搜索每个子文件夹,直到您的dirname为每个子目录返回一个空单元格。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2652630

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档