What's wrong with my code for " rename a bunch of files in a folder "

2 次查看(过去 30 天)
Hi everyone , I want to rename a bunch of files in a folder ,
here is code
clear;clc;
str = dir('C:\Users\user\Desktop\結果圖\*.jpg'); % folder
strx = struct2cell(str);
sn = length(strx(1,:));
for ix = 1:sn
newname=sprintf('0%d.jpg',ix);
movefile(strx{1,ix},newname);
end
it was work , but recently it can not work and shows Error massage
??? Error using ==> movefile
Cannot copy or move a file or directory onto itself.
Why it was work , but it is not now .
ps.
if the first file in the folder is named "01.jpg" then the error is
??? Error using ==> movefile
Cannot copy or move a file or directory onto itself.
if the first file in the folder is named "02.jpg" then the error is
??? Error using ==> movefile
No matching files were found.

回答(1 个)

Sean de Wolski
Sean de Wolski 2014-4-16
I get this error when the filename is the old filename is the same as the new filename:
movefile('A.mat','A.mat')
Error using movefile
Cannot copy or move a file or directory onto
itself.
If you don't want to rename all of the files, i.e. the ones that already have the new name are all set, then just skip that iteration
for ix = 1:sn
newname=sprintf('0%d.jpg',ix);
if ~isequal(strx{1,ix},newname) % if the names are different
movefile(strx{1,ix},newname);
end
end
  2 个评论
Sean de Wolski
Sean de Wolski 2014-4-16
This means it's trying to move a file that doesn't exist:
movefile('HelloWorld.mat','A.mat')
Run the following:
dbstop if error
Which will stop with the debugger when the error is thrown so you can inspect the filename that does not exist.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by