how Modify text file ,Write new values
조회 수: 4 (최근 30일)
이전 댓글 표시
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
답변 (1개)
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!