我需要将所有这些文件放在D:\dic
下,并循环遍历它们,以便进一步单独处理。
MATLAB支持这种操作吗?
它可以在其他脚本中完成,如PHP、Python…
发布于 2010-04-16 21:41: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: []
发布于 2014-10-19 17:19:17
我使用了this great answer中提到的代码,并对其进行了扩展,以支持我在本例中需要的两个附加参数。这些参数是要筛选的文件扩展名,以及指示是否将完整路径连接到文件名的标志。
我希望它足够清楚,有人会发现它是有益的。
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
发布于 2010-04-16 22:59:25
您可以使用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循环中,并继续搜索每个子文件夹,直到您的dirname为每个子目录返回一个空单元格。
https://stackoverflow.com/questions/2652630
复制相似问题