Experts, I am trying to rename some images with the following code. The new names should be '1.jpg', '2.jpg' etc. However, I get ' 1.jpg', ' 2.jpg' etc. Note there is a space before each digit. What is the issue with my code?
a ='C:\Users\Faraz\Desktop\IBHS\Flame height\Frames\';
A =dir( fullfile(a, '*.jpg') );
fileNames = { A.name };
for iFile = 1 : numel( A )
newName = fullfile(a, sprintf( '%2d.jpg', iFile ) );
movefile( fullfile(a, fileNames{ iFile }), newName );
end

 採用された回答

Walter Roberson
Walter Roberson 2018 年 4 月 10 日

0 投票

%2d means that it should always take a minimum of 2 characters for the number. %d would use the minimum length for each number.
If you were looking for 01.jpg, 02.jpg, ... 09.jpg, 10.jpg, etc., then you would use %02d

5 件のコメント

Tala Hed
Tala Hed 2018 年 4 月 10 日
Thank you for your response. when I use %d, I Get the following error:
Error using movefile Cannot copy or move a file or directory onto itself.
Error in kkksher (line 7) movefile( fullfile(a, fileNames{ iFile }), newName );
Walter Roberson
Walter Roberson 2018 年 4 月 10 日
You tried to move (for example) 2.jpg to 2.jpg
You have the general problem that you might have input files that sort before digits but also have files names with digits that you do not want to clobber. It is not robust to move without verifying the output names first. I suggest creating a temporary directory first and moving them to there in order, and then move back from the temporary directory. (There are other algorithms possible.)
Tala Hed
Tala Hed 2018 年 4 月 10 日
I am so confused Walter! Let me ask my question like this! I want to rename some images. The current names are: 1.jpg, 13.jpg, 25.jpg, etc. The new names should be 1.jpg, 2.jpg, 3.jpg ... Thank you in advance
Walter Roberson
Walter Roberson 2018 年 4 月 10 日
a ='C:\Users\Faraz\Desktop\IBHS\Flame height\Frames\';
A = dir( fullfile(a, '*.jpg') );
fileNames = fullfile(a, {A.name} );
for iFile = 1 : length(fileNames)
oldName = fileNames{iFile};
newName = fullfile(a, sprintf( '%d.jpg', iFile ) );
if ~strcmp(oldName, newName)
movefile( oldName, newName );
end
end
Tala Hed
Tala Hed 2018 年 4 月 10 日
Thank you, Walter

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeSearch Path についてさらに検索

タグ

質問済み:

2018 年 4 月 10 日

コメント済み:

2018 年 4 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by