Trouble using movefile to change filenames
4 ビュー (過去 30 日間)
古いコメントを表示
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
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...
採用された回答
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 件のコメント
その他の回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!