Effacer les filtres
Effacer les filtres

Trouble using movefile to change filenames

17 vues (au cours des 30 derniers jours)
Will
Will le 6 Août 2014
Commenté : Star Strider le 6 Août 2014
I have a code designed to rename a folder full of files by changing the numbers to 4 digits. for example a file text_#1.txt would be changed to text_#0001.txt. It is working perfectly unless the number is already four digits long in which case this error appears:
Error using movefile Cannot copy or move a file or directory onto itself.
Here is the script I am using:
for k = 1:numel(j)
name = j(k).name; %store the names in a variable
nums = regexp(name,'\d*','match'); %store individual name in variable
oldstr = cell2mat(nums(end)); %the old string as a number
newstr = num2str(sprintf('%04d',str2num(cell2mat(nums(end))))); %the new string as a number
old = fullfile(folder,name); %the old file
new = strrep(fullfile(folder,name),sprintf('#%s',oldstr),sprintf('#%s',newstr)); %the new filename
comp = strcmp(oldstr,newstr);
if comp == 0
movefile(old,new) %change the filenames
else
continue
end
end
it does not work when it reaches a file such as text_#1000. because this already has 4 digits the old and new filenames are identical and matlab returns the above error.
I want it to skip the file if it is already in the correct format but the same error message keeps appearing. I also tried using a try, catch loop instead of if,else. If anyone can help it would be much appreciated.
  4 commentaires
dpb
dpb le 6 Août 2014
Superficially, logic looks ok...I might rewrite the conditional as
if ~comp
movefile(old,new) %change the filenames
end
since the 'continue' is superfluous given it's placement in the loop, but that's really immaterial.
Use the debugger and step thru with one of the failing name patterns and see where the logic actual goes wrong...
Will
Will le 6 Août 2014
turns out it works either way. i got so caught up in the script i had matlab in the wrong folder. thanks anyway

Connectez-vous pour commenter.

Réponse acceptée

Star Strider
Star Strider le 6 Août 2014
Modifié(e) : Star Strider le 6 Août 2014
I would use exist instead of ‘comp == 0’, something like:
if ~exist(newstr,'file')
movefile(old,new) %change the filenames
else
continue
end
No promises because I can’t test your code, but first testing to see if the file already exists would prevent the error.
  2 commentaires
Will
Will le 6 Août 2014
Modifié(e) : Will le 6 Août 2014
turns out it works either way. i got so caught up in the script i had matlab in the wrong folder. thanks anyway
Star Strider
Star Strider le 6 Août 2014
My pleasure!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by