autorename if saved file already exist

조회 수: 53(최근 30일)
Luca Cavazzana
Luca Cavazzana 2012년 1월 14일
댓글: Diaa 2020년 10월 16일
is there an option in save (or any other function) which support automatic renaming if the filename already exists or do I need to check by myself? (like saving as file2.mat if file.mat already exist)

채택된 답변

Jan 2012년 1월 14일
You have to check it by your own if a file is existing already.
[EDITED: Consider {File.txt, File3.txt}]
function SaveWithNumber(FileName, Data)
[fPath, fName, fExt] = fileparts(FileName);
if isempty(fExt) % No '.mat' in FileName
fExt = '.mat';
FileName = fullfile(fPath, [fName, fExt]);
if exist(FileName, 'file')
% Get number of files:
fDir = dir(fullfile(fPath, [fName, '*', fExt]);
fStr = lower(sprintf('%s*',;
fNum = sscanf(fStr, [fName, '%d', fExt, '*']);
newNum = max(fNum) + 1;
FileName = fullfile(fPath, [fName, sprintf('%d', newNum), fExt]);
save(FileName, 'Data');
Limitations: "FileNameInf.txt" and "FileNameNaN.txt" will cause troubles...
Consider, that:
exist(FileName, 'file')
replies TRUE for directories also.
  댓글 수: 2
Jan 2012년 1월 14일
My "nice" function is too lazy: Imagine these files are existing already: File.txt, File3.txt. Now the user wants to save File.txt - now the function tries to create File3.txt and fails recursively.
I'm posting a new version, which is hopefully smarter.

댓글을 달려면 로그인하십시오.

추가 답변(1개)

Diaa 2020년 10월 1일
편집: Diaa 2020년 10월 1일
Revisitng this old question, I followed the idea of Jan to come up with this solution of appending the existent file name with an incremental number enclosed in parentheses.
if exist(filename,'file')
[fPath, fName, fExt] = fileparts(filename);
fDir = dir(fullfile(fPath, [fName,' (*)', fExt]));
if isempty(fDir)
filename = fullfile(fPath, [fName,' (1)', fExt]);
pattern = "(" + digitsPattern + ")" + fExt;
hasThePattern = endsWith(extractfield(fDir,'name'),pattern);
Extracted = extract(extractfield(fDir(hasThePattern),'name'),pattern);
num = max(cell2mat(cellfun(@(C) textscan(C,'(%d)') , Extracted,'UniformOutput',true)));
num = num+1;
filename = fullfile(fPath, [fName,' (',num2str(num),')', fExt]);
  댓글 수: 2
Diaa 2020년 10월 16일
Nice and consice approach but it will intuitively fail when you have in your folder
file name
file name (1)
file name (3)
as your code will create a new file
file name (2)
with a number smaller than the existent max one (i.e. 3), and hence it will mislead the user to make him/her think the file name (3) is newer, which is not.

댓글을 달려면 로그인하십시오.


Find more on File Operations in Help Center and File Exchange



Community Treasure Hunt

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

Start Hunting!

Translated by