【问题标题】:Selecting Randon files from a folder tree从文件夹树中选择 Randon 文件
【发布时间】:2014-07-04 20:35:38
【问题描述】:

我有这个文件夹组织

root/folder_1/file1_1 --up to-- file_5693
root/folder_2/file2_1 --up to-- file_100
root/folder_3/file3_1 --up to-- file_600
root/folder_4/file4_1 --up to-- file_689

我想在每个文件夹中选择一些(例如 1000 个)随机文件并将它们放在一个输出文件夹中,但是对于少于 200 个文件的文件夹,我想复制所有文件。

root_2/output:
file1_350
.
.
.
file2_1 --> file2_100
.
.
.
etc

我该怎么做?

我尝试使用dir 命令列出目录中的所有文件夹名称,但文件夹编号不连续。有什么帮助吗?

【问题讨论】:

    标签: matlab file-io directory


    【解决方案1】:

    我可能会误解,但我没有看到订购文件夹名称的理由,因为无论如何您都会复制它们。 以下是在文件夹中复制文件的脚本,该脚本再次位于根目录中。

    您只需更改以下四个变量ROOT_DIROUT_DIRTHRESHOLD_COPYN_RANDOM_COPY

    % Define 
    ROOT_DIR = './'; % where the subdirectories are located
    OUT_DIR = './root2'; % copy destination
    THRESHOLD_COPY = 200; % threshold for copying all files
    N_RANDOM_COPY = 100; % number of files that you want to copy
    
    dirList = dir(ROOT_DIR);
    dirList = dirList(3:end); % first two are ./ and ../
    dirOnlyIndicators = cell2mat({dirList.isdir});
    
    dirs = dirList(dirOnlyIndicators);
    for dirIterator = transpose(dirs)
      subdirList = dir([ ROOT_DIR dirIterator.name]);
      fileIndicators = ~cell2mat({subdirList.isdir});
      subfileList = {subdirList(fileIndicators)};
      nFiles = sum(fileIndicators);
      copyIndices = [];
      if nFiles > THRESHOLD_COPY
        copyIndices = randperm(nFiles);
        copyIndices = copyIndices(1:N_RANDOM_COPY);
      else
        copyIndices = 1:nFiles;
      end
    
      for copyIndex = copyIndices
          copyfile([ ROOT_DIR dirIterator.name '/' subfileList{copyIndex}.name],...
            [OUT_DIR '/' subfileList{copyIndex}.name],...
            'f');
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      • 2020-11-24
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多