【问题标题】:Recursive listing of directories in Matlab [duplicate]Matlab中目录的递归列表[重复]
【发布时间】:2013-04-09 14:15:44
【问题描述】:

我有一个包含 3 个文件夹的目录。这 3 个文件夹中的每个文件夹都有其他数量的文件夹。在这些文件夹的每个文件夹中,都有一个文件列表,我想在每个文件上运行代码。例如: 就像这样: MainFolder 有 SubFolder1、SubFolder2。 SubFolder1 有 SubSubFolder1、SubSubFolder2、SubSubFolder3。 SubFolder2 有 SubSubFolder1、SubSubFolder2。 每个 SunSubFolders 都有许多文件。 我想要一个脚本,我给它 MainFolder Path,它遍历每个子文件夹和子子文件夹,并对这个子文件夹中的文件进行操作,并用这个子文件夹的名称保存工作区。因此,在上面的示例中,在对 SubSubFolder1 中的文件进行一些处理之后,生成的工作空间将保存在名为 SubSubFolder1.mat 的位置中。

请问是否有人可以帮助我,因为这对我来说相当紧急。 非常感谢您的帮助和考虑。

更新:

我已经完成了,但是出现了另一个问题,当我访问 SubSubFolders 中的文件并尝试进行操作时,它显示“无法打开文件 '[00000000].pgm',因为:没有这样的文件或目录”。 如何解决这个问题?

这是我的代码:

D = rdir('Hussein/*/*');           %// List of all sub-directories
for k = 1:length(D)
    currpath = D(k).name;                 %// Name of current directory
    [pathstr, name, ext] = fileparts(currpath);
    %// Operate on all .txt files in currpath
    l = dir(fullfile(currpath, '*.pgm')); %// Listing of all relevant files
    filenames={l.name}';

    nfiles=length(filenames)
    %images=zeros(240, 320, 1000);
    idx=1;

    strtidx=1;
    endidx=nfiles;
    step=1;

    waitbar(0);
    for i=strtidx:step:endidx
        fn=fullfile('', filenames{i});
        tmp=padarray(ut_pgmread(fn), 1, 'post');
        %figure(1); imagesc(tmp); colormap(jet(4096)); colorbar;

        images(:, :, idx)=tmp; idx=idx+1;

        waitbar(i/nfiles);
    end

    close(findall(0,'Tag','TMWWaitbar'));
    name='/Volumes/Untitled/work/'+name;
    save (name, '-v7.3');

    %for m = 1:length(F)
     %   currfile = F(m).name;             %// Name of current file

        %// Do something with currfile...
    %end

    %// Write output (if any) in currpath...
end;

【问题讨论】:

  • 只要在 SO 中搜索,您就会得到几乎完整的答案:stackoverflow.com/questions/8748976/…
  • @Robocop 这不是递归目录列表,因此不是重复的。
  • @EitanT 我已经更新了这个问题,所以如果你可以请检查一下。
  • @EitanT 感谢 Eitan,我能够使用 cd 解决它

标签: matlab


【解决方案1】:

您似乎正在寻找 dir 的递归版本,因此您可能会发现 MATLAB File Exchange 中的 enhanced rdir tool 对您的目的有用。使用增强的rdir,您的代码将看起来类似于以下内容:

%// List all sub-directories under MainFolder recursively
D = rdir('MainFolder\**\*.');             %// List of all sub-directories
for k = 1:length(D)
    currpath = D(k).name;                 %// Name of current directory

    %// Operate on all .txt files in currpath
    F = dir(fullfile(currpath, '*.txt')); %// Listing of all relevant files
    for m = 1:length(F)
        currfile = F(m).name;             %// Name of current file

        %// Do something with currfile...
    end

    %// Write output (if any) in currpath...
end;

【讨论】:

    猜你喜欢
    • 2013-08-17
    • 2017-07-15
    • 2018-05-23
    • 2011-03-10
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    相关资源
    最近更新 更多