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

1 Ansicht (letzte 30 Tage)
Tai-i
Tai-i am 16 Apr. 2014
Kommentiert: Sean de Wolski am 16 Apr. 2014
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.

Antworten (1)

Sean de Wolski
Sean de Wolski am 16 Apr. 2014
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 Kommentare
Tai-i
Tai-i am 16 Apr. 2014
it still get error
??? Error using ==> movefile
No matching files were found.
Sean de Wolski
Sean de Wolski am 16 Apr. 2014
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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu File Operations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by