How to create files by changing name after checking existance

2 visualizaciones (últimos 30 días)
Mohamed Ismail Benabdelhadi
Mohamed Ismail Benabdelhadi el 17 de Sept. de 2020
Editada: Prabhanjan Mentla el 21 de Sept. de 2020
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

Respuestas (1)

Prabhanjan Mentla
Prabhanjan Mentla el 21 de Sept. de 2020
Editada: Prabhanjan Mentla el 21 de Sept. de 2020
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.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos


Versión

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by