Octave: Load all files from specific directory

醉酒当歌 提交于 2019-12-06 07:06:58

It's usually bad design if you load files to variables which name is generated dynamically and you should load them to a cell array instead but this should work:

files = glob('C:\folder\*.txt')
for i=1:numel(files)
  [~, name] = fileparts (files{i});
  eval(sprintf('%s = load("%s", "-ascii");', name, files{i}));
endfor

The function scanFiles searches file names with extensions in the current dirrectory (initialPath) and subdirectories recursively. The parameter fileHandler is a function that you can use to process populated file structure (i.e. read text, load image, etc.)

Source

function scanFiles(initialPath, extensions, fileHandler)
  persistent total = 0;
  persistent depth = 0; depth++;
  initialDir = dir(initialPath);

  printf('Scanning the directory %s ...\n', initialPath);

  for idx = 1 : length(initialDir) 
    curDir = initialDir(idx);
    curPath = strcat(curDir.folder, '\', curDir.name);

    if regexp(curDir.name, "(?!(\\.\\.?)).*") * curDir.isdir
      scanFiles(curPath, extensions, fileHandler);
    elseif regexp(curDir.name, cstrcat("\\.(?i:)(?:", extensions, ")$"))
      total++;
      file = struct("name",curDir.name,
                     "path",curPath,
                     "parent",regexp(curDir.folder,'[^\\\/]*$','match'),
                     "bytes",curDir.bytes);
      fileHandler(file);
    endif
  end

  if!(--depth)
    printf('Total number of files:%d\n', total);
    total=0;
  endif
endfunction

Usage

# txt
# textFileHandlerFunc=@(file)fprintf('%s',fileread(file.path));
# scanFiles("E:\\Examples\\project\\", "txt", textFileHandlerFunc);

# images
# imageFileHandlerFunc=@(file)imread(file.path);
# scanFiles("E:\\Examples\\project\\datasets\\", "jpg|png", imageFileHandlerFunc);

# list files
fileHandlerFunc=@(file)fprintf('path=%s\nname=%s\nsize=%d bytes\nparent=%s\n\n',
               file.path,file.name,file.bytes,file.parent);
scanFiles("E:\\Examples\\project\\", "txt", fileHandlerFunc);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!