Renaming folders within folders to the name of original folder
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello,
I have one big folder, lets call "data", which has folders inside called 'person'.
Each "person" has specific folders, sometimes "SE1" and "SE3", sometimes SE1 and SE8, etc..., it's random.
I want these this SE1, SE2, folders, etc, to be renamed to "person1 SE1" , "person 1 SE3" "Person2 SE1" "Person2 SE9" etc...
essentially to be the name of the folder it's in, but keeping it's current foldername.
Can someone help formulate a script for me? I'm very new to Matlab.
thank you!!
0 commentaires
Réponses (1)
Sourabh Kondapaka
le 11 Fév 2021
Modifié(e) : Sourabh Kondapaka
le 11 Fév 2021
Check out the below code
% This is the path to data folder
pathToData = fullfile(pwd, 'data');
dataFolder = dir(pathToData);
dirFlags = [dataFolder.isdir];
subFolders = dataFolder(dirFlags);
%Considering values from 3rd index to not include '.' and '..'
subFolders = subFolders(3:length(subFolders));
for k = 1 : length(subFolders)
% Get the name of the person folder within data folder
person = subFolders(k).name;
personSubFolder = dir(fullfile(pathToData, person));
% Get subFolders within the person folder. Excluding '.' and '..'
personSubFolder = personSubFolder(3:length(personSubFolder));
for j = 1: length(personSubFolder)
seFolder = personSubFolder(j).name;
% srcFolder is the original folder. destFolder is the new Name of the folder
% I'm using the movefile() function to rename accordingly
srcFolder = fullfile(pathToData, person, seFolder);
destFolder = fullfile(pathToData, person, person + " " + seFolder);
movefile(srcFolder, destFolder);
% fprintf('\n \n ------------- Renaming from ---------- \n \n');
% disp(srcFolder);
% fprintf('\n \n To \n \n');
% disp(destFolder);
end
end
Initial Folder Structure:
After executing the above script:
A similar question has been answered here
You can take the free course Matlab OnRamp
Note: As your query was simple enough, a for-loop approach was sufficient. If you need to achieve something much more complicated than this, please read up about Recursion, Backtracking
1 commentaire
Stephen23
le 11 Fév 2021
Modifié(e) : Stephen23
le 11 Fév 2021
A very good answer, but let down by this one piece of poor advice:
%Considering values from 3rd index to not include '.' and '..'
subFolders = subFolders(3:length(subFolders)); % FRAGILE AND MISLEADING
Much better advice:
As Walter Roberson wrote in that last link: "In short: if your code assumes that '.' and '..' are the first two entries in a directory, your code has a bug (even in MS Windows). If your code assumes that directory entries are returned in any sorted order, your code has a bug (in all OS.)"
Voir également
Catégories
En savoir plus sur File Operations dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!