How to create files by changing name after checking existance

4 ビュー (過去 30 日間)
Mohamed Ismail Benabdelhadi
Mohamed Ismail Benabdelhadi 2020 年 9 月 17 日
編集済み: Prabhanjan Mentla 2020 年 9 月 21 日
Hi,
I have a code that is capable of generating different arrays of geometry at each run. And I would like to store this arrays in a .csv or .txt file at each run. So basically,
  • I run the code, then an array of numbers is generated and is stored under the name 'name_2D_1'
  • Then each time I run the code again, it checks if there is already a file named 'name_2D_1' and if it's the case, he stores the data in a new file named 'name_2D_2', so basically, it creates a new file with an incremented file name at each run.
It's the first time I'm trying to do such a thing, so I don't exactly how to manipulate the syntax to achieve the steps I want to execute. Any help would be very much appreciated and I'm eager to learn.
This is what I have tried so far, but it's not working as the index incrementation is not correctly placed.
Thanks a lot in advance,
folder = 'C:\Users\username\Desktop\selectedfolder';
index = 1;
filename = 'name_2D_1';
% filename = fullfile(folder, baseFileName, '.txt');
while index < 500
if exist(filename, 'file')
k = sscanf(filename, '%f');
k = k+1;
formatSpec = 'name_2D_%d.txt';
filename = sprintf(formatSpec,k)
save(filename, 'average_line', '-ascii', '-double', '-tabs');
index = index + 1
else
break
end
end

回答 (1 件)

Prabhanjan Mentla
Prabhanjan Mentla 2020 年 9 月 21 日
編集済み: Prabhanjan Mentla 2020 年 9 月 21 日
Hi,
Each time when the code run, it checks whether any existing files are present, starting from name_2D_1.txt.
folder = 'C:\Users\Username\Desktop\temp';
index = 1;
filename = 'name_2D_1.txt';
while index < 10
if exist(filename,'file')==0 % check if the fileexists with that name
newfilename = sprintf('name_2D_%d.txt',index);
save(newfilename);
end
index = index + 1; % if file exists, then come here and search for next possible name
filename = sprintf('name_2D_%d.txt',index);
end
The above code helps to check the existence condition prior to saving into folder.
Hope this helps.

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by