autorename if saved file already exist
이전 댓글 표시
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)
채택된 답변
추가 답변 (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]);
else
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]);
end
end
댓글 수: 4
Joshua Grosserhode
2020년 10월 16일
Nice clean solution. Since I do not yet have 2020b, I used this solution:
num = 0;
while exist(FileName, 'file')
num = num+1;
FileName = fullfile(outFolder, [fName,' (',num2str(num),')', fExt]);
end
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.
Mohammed Attrash
2023년 7월 9일
You can add to your file name the following
datestr(now,'dd.mm.yyyy_HH.MM')
This will create a unique name
It can sometimes be important to preserve the file extension, so make sure that is added before the extension.
These days it is better to use
string(datetime('now', 'format', 'uuuu.MM.dd_HH.mm'))
카테고리
도움말 센터 및 File Exchange에서 Standard File Formats에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!