胡子哥哥
2019-07-26 15:58:14
如何在MATLAB中獲取特定目錄下的所有文件?我需要獲取所有這些文件D:\dic并循環(huán)它們以進一步單獨處理。MATLAB是否支持這種操作?它可以在其他腳本中完成,如PHP,Python ......
3 回答

翻閱古今
TA貢獻1780條經驗 獲得超5個贊
鑒于這篇文章相當陳舊,我在這段時間內為自己的用途修改了這個實用程序,我想我應該發(fā)布一個新版本。我的最新代碼可以在The MathWorks File Exchange上找到:dirPlus.m
。您也可以從GitHub獲取源代碼。
我做了很多改進。它現(xiàn)在為您提供了前置完整路徑或僅返回文件名(從Doresoom和Oz Radiano合并)的選項,并將正則表達式模式應用于文件名(由Peter D合并)。此外,我添加了將驗證功能應用于每個文件的功能,允許您根據(jù)標準以外的條件(即文件大小,內容,創(chuàng)建日期等)選擇它們。
注意:在較新版本的MATLAB(R2016b及更高版本)中,該dir
功能具有遞歸搜索功能!因此,您可以執(zhí)行此操作以獲取*.m
當前文件夾的所有子文件夾中的所有文件的列表:
dirData = dir('**/*.m');
舊代碼:(后代)
這是一個以遞歸方式搜索給定目錄的所有子目錄的函數(shù),收集它找到的所有文件名的列表:
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 endend
在MATLAB路徑的某處保存上述函數(shù)后,可以通過以下方式調用它:
fileList = getAllFiles('D:\dic');
添加回答
舉報
0/150
提交
取消