how Modify text file ,Write new values
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi: I have a text file that is an input file to a simulator program and I want to change some input variables and transfer them back to the simulator program (for example afw in row 48 of column 8), when I do this May_made changes in MATLAB but the text file in the main folder still does not change, please help
filename=fullfile('D:\','app','try1','TRY1B','w2_con.npt ');
fid = fopen(filename,'r');
format = repmat('%s',[1,10]);
A = textscan(fid,format);
A=[A{:}];
fclose(fid);
% Change cell A
A{48,8}=sprintf('%d',6);
0 comentarios
Respuestas (1)
Walter Roberson
el 28 de Dic. de 2020
%do not overwrite the old file; we are counting on the old field being 15.0000
filename = fullfile('D:\','app','try1','TRY1B','w2_con.npt ');
newfile = fullfile('D:\','app','try1','TRY1B','new_w2_con.npt ');
S = regexp( fileread(filename), '\n', 'split');
newval = 6;
S{48} = regexprep(S{48}, '15\.0000', sprintf('%.4f', newval), 'once');
S = strjoin(S, '\n');
[fid, msg] = fopen(newfile, 'w'); %not 'wt'
if fid < 0
error('Failed to open file "%s" for writing because "%s"', newfile, msg);
end
fwrite(fid, S);
fclose(fid);
If you cannot count on the field to replace being a specific value, then you may have to replace by position, which can be a bit tricky as it looks like you might possibly be using fixed width fields (or possibly they are tab separated.)
Your existing code to read the fields is not going to do well on lines such as
WB 1 ET OFF OFF ON OFF 15.0000 2.00000 2.00000 10.0000
as the character fields are permitted to have embedded blanks which you are reading in as separate fields.
0 comentarios
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!