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

1 回表示 (過去 30 日間)
Tai-i
Tai-i 2014 年 4 月 16 日
コメント済み: Sean de Wolski 2014 年 4 月 16 日
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 件のコメント
Tai-i
Tai-i 2014 年 4 月 16 日
it still get error
??? Error using ==> movefile
No matching files were found.
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 Center および File ExchangeFile Operations についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by