Trouble using movefile to change filenames

조회 수: 7 (최근 30일)
Will
Will 2014년 8월 6일
댓글: Star Strider 2014년 8월 6일
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
dpb
dpb 2014년 8월 6일
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 2014년 8월 6일
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 2014년 8월 6일
편집: Star Strider 2014년 8월 6일
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
Will
Will 2014년 8월 6일
편집: Will 2014년 8월 6일
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 2014년 8월 6일
My pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Historical Contests에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by