Copy Files from Subfolders with Specific File Names in MATLAB
Copy 'ar.nii' Files from Subfolders in MATLAB
This MATLAB code snippet helps you copy files named 'ar.nii' from multiple subfolders within a main folder to a new destination folder. The script iterates through each subfolder and copies the target file to the new location while maintaining the original subfolder names.
% Path of the main folder
mainFolderPath = 'path/to/main/folder';
% Path of the new folder
newFolderPath = 'path/to/new/folder';
% Get information of all subfolders in the main folder
subfolders = dir(mainFolderPath);
% Iterate through all subfolders
for i = 1:numel(subfolders)
% Ignore '.' and '..' subfolders
if strcmp(subfolders(i).name, '.') || strcmp(subfolders(i).name, '..')
continue;
end
% Build the full path of the subfolder
folderPath = fullfile(mainFolderPath, subfolders(i).name);
% Check if the subfolder contains the 'ar.nii' file
if exist(fullfile(folderPath, 'ar.nii'), 'file')
% Copy the 'ar.nii' file to the new folder while keeping the original folder name
copyfile(fullfile(folderPath, 'ar.nii'), fullfile(newFolderPath, subfolders(i).name));
end
end
Explanation:
- Set Paths: Replace 'path/to/main/folder' and 'path/to/new/folder' with your actual main folder and desired destination folder paths, respectively.
- Get Subfolders: The
dir(mainFolderPath)command retrieves information about all files and folders within themainFolderPath. - Iterate and Filter: The code iterates through each item listed in
subfolders. It usesstrcmpto skip the '.' and '..' directories, which represent the current and parent directory respectively. - Construct Subfolder Path: For each valid subfolder,
fullfile(mainFolderPath, subfolders(i).name)constructs the complete path to that subfolder. - Check for Target File:
exist(fullfile(folderPath, 'ar.nii'), 'file')checks if the 'ar.nii' file exists within the current subfolder. - Copy File: If the file exists,
copyfilecopies it from the subfolder to the new folder. The destination path includes the original subfolder name (subfolders(i).name) to maintain the folder structure.
This script provides a structured way to manage and copy specific files across multiple subfolders in MATLAB.
原文地址: https://www.cveoy.top/t/topic/pps 著作权归作者所有。请勿转载和采集!