我有无数文件夹需要访问并删除其中的前6个文件。目前,我有一个代码进入该文件夹,并一次删除一个文件。我似乎无法弄清楚如何创建一个循环来简化这段代码。
FN_NIFTI = 'C: path';
funcdir = 'C: path'/folder';
FNruns = {'Folder 1', 'Folder 2', 'Folder 3', etc..};
for i=1:length(FNruns)
delete(fullfile(FN_NIFTI,funcdir,FNruns{i},'*001.nii'))
delete(fullfile(FN_NIFTI,funcdir,FNruns{i},'*002.nii'))
delete(fullfile(FN_NIFTI,funcdir,FNruns{i},'*003.nii'))
delete(fullfile(FN_NIFTI,funcdir,FNruns{i},'*004.nii'))
delete(fullfile(FN_NIFTI,funcdir,FNruns{i},'*005.nii'))
delete(fullfile(FN_NIFTI,funcdir,FNruns{i},'*006.nii'))
end
请注意,上面的代码会被复制/粘贴多次。例如,我在其下面有另一个代码,例如:
ASL_NIFTI = 'C: path';
funcdir = 'C: path'/folder';
ASLruns = {'Folder 1', 'Folder 2', 'Folder 3', etc..};
for i=1:length(NWruns)
delete(fullfile(ASL_NIFTI ,funcdir,ASLruns {i},'*001.nii'))
delete(fullfile(ASL_NIFTI ,funcdir,ASLruns {i},'*002.nii'))
delete(fullfile(ASL_NIFTI ,funcdir,ASLruns {i},'*003.nii'))
delete(fullfile(ASL_NIFTI ,funcdir,ASLruns {i},'*004.nii'))
delete(fullfile(ASL_NIFTI ,funcdir,ASLruns {i},'*005.nii'))
delete(fullfile(ASL_NIFTI ,funcdir,ASLruns {i},'*006.nii'))
end
我很感激帮助! (请给初学者解释)
由于
答案 0 :(得分:0)
你可以从改善for循环开始。
for i = 1:length(targetFolder)
for fileNr = 1:6
delete(fullfile(targetFolder{i}, sprintf('*00%d.nii', fileNr)));
end
end
变量targetFolder
应包含您要删除文件的所有文件夹。如果以特殊方式选择了theese文件夹,您可以将它们排成一行:
targetFolder = { ...
fullfile(FNrunsRootDir, FolderA), ...
fullfile(FNrunsRootDir, FolderC), ...
...
fullfile(ALSrunsRootDir, FolderX), ...
fullfile(ALSrunsRootDir, FolderY), ...
...
};
如果 all 应该挑选每个根文件夹中的子文件夹,您可以使用dir
来获取它们
rootDirs = {FNrunsRootDir, ALSrunsRootDir, ...}
for iDir = 1:length(rootDirs)
subDirs = dir(rootDirs{iDir});
% Pick out all valid sub folders
subDir = setdiff({subDir([subDir.isdir]).name}, {'.','..'});
% Combine into full folder paths
targetFolder = strcat(rootDirs{i}, filesep, subDir);
%%%% FOR LOOP FROM ABOVE GOES HERE %%%%
end