Why is Movefile creating a folder instead of renaming a file?

7 views (last 30 days)
The program:
for k = 1:1
Folder = sprintf('/Users/NaomiGaggi/Desktop/GroupAnalysis/sub%d/STRUC/', k);
movefile(fullfile(Folder, '*.nii'),fullfile(Folder, 'T1.nii'));
end
makes a FOLDER T1.nii instead of renaming the file containing the extension .nii to T1.nii.
Does anyone know how to fix this?
Thanks!

Accepted Answer

Stephen23
Stephen23 on 18 Oct 2018
Edited: Stephen23 on 18 Oct 2018
When renaming a file using movefile you can only specify one file for the first input: "To rename a file or folder when moving it, make destination a different name from source and specify only one file or folder for source."
However your code uses the asterisk * to specify that the first input can match multiple files, so the second input is therefore interpreted as a folder. It is not possible to rename multiple files (indicated by an asterisk) using just one filename, so the only reasonable interpretation of the second input is as a folder name. Note that this is true even if the wildcard only matches one file, because otherwise the behavior would change depending on how many files it matches! Therefore an asterisk in the first input always indicates that the second input is a folder.
Solution: you will need to get the actual name of the file to use as the first input, something like this:
D = 'Users/NaomiGaggi/Desktop/GroupAnalysis';
for k = 1:1
F = sprintf('sub%d',k);
S = dir(fullfile(D,F,'STRUC','*.nii'));
assert(numel(S)==1,'Must match one file!')
Z = fullfile(D,F,'STRUC','T1.nii');
movefile(S.name,Z)
end
  3 Comments
Stephen23
Stephen23 on 18 Oct 2018
" So, I ran the program but I am getting an error with line 5(the assert command)."
If dir matches zero or multiple files then that assert will detect this (which is why I put it there). And now it turns out that you actually have zero/multiple files matching that pattern. You need to think about this:
  • If there are zero files, do you want to ignore this, or throw an error?
  • If there are multiple files, how do you expect to rename multiple files with the same filename T1.nii ?
Remember that movefile can only rename one file at a time!
"This was also a very helpful answer, I appreciate it!!"
You can show your appreciation by accepting and voting for answers.

Sign in to comment.

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!