how Modify text file ,Write new values

2 ビュー (過去 30 日間)
mozhgan gholami
mozhgan gholami 2020 年 12 月 28 日
回答済み: Walter Roberson 2020 年 12 月 28 日
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);

回答 (1 件)

Walter Roberson
Walter Roberson 2020 年 12 月 28 日
%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.

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by