MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   如何在MATLAB中的特定目录下获取所有文件? (https://www.labfans.com/bbs/showthread.php?t=23322)

poster 2019-12-10 20:30

如何在MATLAB中的特定目录下获取所有文件?
 
我需要将所有这些文件放在D:\dic并循环遍历,以分别进行进一步处理。

MATLAB是否支持这种操作?

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



[B]回答:[/B]

[B]更新:[/B]鉴于这篇文章已经很老了,并且在此期间我已经对该实用程序进行了很多修改以供自己使用,所以我认为我应该发布一个新版本。我的最新代码可以在[URL="http://www.mathworks.com/matlabcentral/fileexchange/?s_tid=gn_mlc_fx"]The MathWorks File Exchange[/URL]上找到: [URL="http://www.mathworks.com/matlabcentral/fileexchange/60716-dirPlus"]dirPlus.m[/URL] 。您也可以从[URL="https://github.com/kpeaton/dirPlus"]GitHub[/URL]获取源代码。

我做了一些改进。现在,它为您提供了添加完整路径或仅返回文件名(由[URL="https://stackoverflow.com/questions/2652630/how-to-get-all-files-under-a-specific-directory-in-matlab/2654459#comment2671016_2654459"]Doresoom[/URL]和[URL="https://stackoverflow.com/a/26449095/52738"]Oz Radiano合并[/URL] )以及将正则表达式模式应用于文件名(由[URL="https://stackoverflow.com/questions/2652630/how-to-get-all-files-under-a-specific-directory-in-matlab/2654459#comment15362987_2654459"]Peter D[/URL]合并)的选项。此外,我还添加了对每个文件应用验证功能的功能,使您可以根据标准(而不是文件名,文件大小,内容,创建日期等)选择文件。

[B]注意:[/B]在较新版本的MATLAB(R2016b和更高版本)中, [URL="https://www.mathworks.com/help/matlab/ref/dir.html"]dir[/URL]函数具有递归搜索功能!因此,您可以执行以下操作以获取当前文件夹的所有子文件夹中所有*.m文件的列表:

dirData = dir('**/*.m'); [B]旧代码:(用于后代) [/B]

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

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');

[url=https://stackoverflow.com/questions/2652630]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 04:58

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.