MATLAB: Rename folders using excel key


Hi everyone,
I am brand new to using MATLAB, so please excuse if this task is very easy.
I have ~300 folders that I have to rename based on an excel spreadsheet key. So the spreadsheet would be with Column A with complete path for the old foldername and Column B will be the new folder name (very easy to change it to path). How can I do that?
Thank you everyone!

Best Answer

  • %assuming no header on the file
    t = readtable('YourExcelKey.xlsx', 'readvariablenames', false);
    for K = 1 : height(t)
    oldfile = t.Var1{K};
    if ~exist(oldfile, 'dir') && ~exist(oldfile, 'file')
    fprintf('no source #%d: "%s"\n', K, oldfile);
    newfile = t.Var2{K};
    if strcmp(oldfile, newfile)
    fprintf('old and new are identical names, #%d: "%s"\n', K, oldfile);
    if exist(newfile, 'dir') || exist(newfile, 'file')
    fprintf('did not move #%d "%s" to "%s" because destination exists\n', K, oldfile, newfile);
    [newdir, lastpart] = fileparts(newfile);
    if ~exist(newdir, 'dir')
    fprintf('target directory #%d does not exist: "%s"\n', K, newdir);
    movefile(oldfile, newfile);
    catch ME
    fprintf('Problem moving #%d "%s" to "%s"\n', K, oldfile, newfile);
    You might want to think more about the target directory not existing case. For example if you asked to move /A/B/C/ to /A/D/E/ and /A/D does not exist, then trying ot move /A/B/C/ directly to /A/D/E/ would fail. The code would test that /A/D exists to move E into and refuse to try if it is not there. What you might want to think about is trying to create all missing levels of the destination path.
    Also, I have the code check to see whether the destination exists already. If you were moving files, then it might be reasonable to move a file over-top of another file. But if you are moving directories and you try to move a directory to another directory, then it would not replace the existing directory, it would move the source into the destination directory, which is probably not what is wanted. Then there is the case where the source is a file but the destination is a directory: would you want the destination directory deleted and replaced with the source file, or would you want the file to be moved into the destination directory? These are usage decisions that have to be made, and in this code I deal with them by not permitting the operation if the destination already exists.