How to check the existence of a file and rename it.

i use matlab in this way: i import a photo (e.g. photo.tif), use an algorithm to edit it and then export the edited in another folder and name it (e.g. photo_n.tif).
the problem is that i want to know if there is already the name of the new photo and then rename it (e.g. photo_n1.tif)
how can i do this without writing a code like "check the existence of photo_n.tif and if there is already one name it photo_n1"
is there a way...?

Answers (2)

Try this - it's fairly robust:
numberSuffix = 1;
baseFileName = 'photo_n';
fullFileName = fullfile(folder, baseFileName, '.tif');
while numberSuffix < 500 % Exit at 500 as a failsafe, just in case all files exist.
if exist(fullFileName, 'file')
% Construct a new filename.
baseFileName = sprintf('photo_n%d.tif', numberSuffix);
fullFileName = fullfile(folder, baseFileName, '.tif');
% Prepare for next time, in case this name also existed.
numberSuffix = numberSuffix + 1;
else
break; % Out of while loop
end
end
s=dir ('yourfolder/yourfilname');
file=s.name
!rename file new_filename
check the existing file by
exist('yourfolder/yourfilname')

Categories

Asked:

on 24 Nov 2012

Community Treasure Hunt

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

Start Hunting!