Append to Text File with For Loop

조회 수: 11 (최근 30일)
Allen Hammack
Allen Hammack 2022년 6월 17일
댓글: Image Analyst 2022년 6월 19일
I am trying to append to a text file using a for loop. Here is a generalized version of my script:
for 1:length(variable)
if isempty(dir(file_name)) == 1
fid = fopen(strcat(pwd,'\',file_name),'w');
fprintf(fid,strcat(repmat('%s\t',1,5),'\n'),...
'Daily Directory',...
'Test Directory',...
'Data File',...
'Position',...
'Maximum');
fclose(fid);
else
end
fid = fopen(strcat(pwd,'\',file_name),'a');
fprintf(fid,strcat(repmat('%s\t',1,5),'\n'),...
daily_directory,...
test_directory,...
file,...
position_id,...
vel_max);
fclose(fid);
end
When I run my script, second fprintf statement appears to overwrite the text that was produced in the previous step through this for loop. For the line
fid = fopen(strcat(pwd,'\',file_name),'a');
I have tried these options: 'a', 'at', and 'a+', but the text continues to be overwritten. Can someone please tell me how to fix my code, such that the text in my text file is appended to instead of being overwritten?
Thanks!
  댓글 수: 5
Voss
Voss 2022년 6월 18일
@Allen Hammack: Regarding accepting my answer: Well, it was a comment, as opposed to an answer per se, so there's no way to accept it (and it didn't address the actual problem, as it turns out).
In any case, I'm glad you got it figured out!
Image Analyst
Image Analyst 2022년 6월 19일
@Voss can make an answer with the same solution below. Then it could be accepted.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by