How to create files by changing name after checking existance
4 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!