Replacing one line (or one part of a line) in a text file
조회 수: 8 (최근 30일)
이전 댓글 표시
Hello. I have a config file that contains 1 specific line that I want to change just the number (in this case from 1000 to e.g. 235)
This is my code so far:
%Get current Value
FilePath='C:\Program Files\Teledyne DALSA\Sapera\CamFiles\User\myCamera.ccf'
Filedata = readlines(FilePath)
TF = contains(Filedata,"Time Integrate Duration=")
k = find(TF,1);
expStr=Filedata(TF);
ReportMessage(app,expStr); %My report function that reports to a UITextarea
oldLine=Filedata(k)
Filedata(k) ="Time Integrate Duration=235" %this is the new line I want
[fid, msg] = fopen('FilePath', 'w')
if fid < 1;
error('could not write output file because "%s"', msg);
end
fwrite(fid, strjoin(Filedata, '\n'));
fclose(fid);
But it doesn't seem to be changing the file
I also enclose the config file (text)
채택된 답변
dpb
2024년 8월 1일
FilePath='C:\Program Files\Teledyne DALSA\Sapera\CamFiles\User';
FileName='myCamera.ccf';
FQName=fullfile(FilePath,FileName); % separate path, name for easy mods, build fully-qualified name
TargetString="Time Integrate Duration="; % I'd make this an argument to the callback function, not hardcoded
NewString="Time Integrate Duration=235"; % make data, not code for flexibility
Filedata=readlines(FQName);
TF=contains(Filedata,TargetString);
if ~any(TF), error('Target String Not Found. Aborting.'); end % make more user-friendly error handler, but gets message across
expStr=Filedata(TF);
ReportMessage(app,expStr); %My report function that reports to a UITextarea
Filedata(TF)=NewString;
writematrix(FileData,FQName) % rewrite the file
You could be a little more general if you were to only replace the numeric value of the target string with a new value; the passing the target and the new value would let you use the routine for any unique target string.
...
NewString=TargetStringNewValue;
Filedata(TF)=NewString;
...
댓글 수: 6
Image Analyst
2024년 8월 1일
@Jason I'm confused by your latest comments. Is it solved or not? You accepted an Answer. Or was the original question solved but now you have additional, different questions? Or are we completely done here?
dpb
2024년 8월 1일
편집: dpb
2024년 8월 1일
@Image Analyst, I think I understand -- I never recall that there is a writelines() now, it wasn't yet introduced in the version I'm running; for it (R2021b) writematrix is the only choice, but requires using the name/value pair 'FileType','text' unless the extension is one of the few recognized ones.
writelines is documented to write text files so it doesn't appear to care about the extension; @Jason just didn't recognize that that would also have fixed his problem; he didn't "need" to replace writematrix although that is certainly the current preferred use; he could have added the file type and continued on.
추가 답변 (1개)
Saurabh
2024년 8월 1일
Hi Jason,
So, the objective is to modify one line in your code or simply you want to re-assign a different value to Time Integrated Duration variable. I have tried to do the same on my end, below you can see the code that I have implemented:
function modify_duration_in_file(file_path, new_duration)
% Read the file
lines = {};
fid = fopen(file_path, 'r');
tline = fgetl(fid);
while ischar(tline)
lines{end+1} = tline;
tline = fgetl(fid);
end
fclose(fid);
% Find and modify the line
for i = 1:length(lines)
if contains(lines{i}, 'Time Integrate Duration=')
parts = strsplit(lines{i}, '=');
parts{2} = num2str(new_duration);
lines{i} = strjoin(parts, '=');
break;
end
end
% Write the file
fid = fopen(file_path, 'w');
for i = 1:length(lines)
fprintf(fid, '%s\n', lines{i});
end
fclose(fid);
end
% Example usage
file_path = 'path/to/your/textfile.txt';
new_duration = 235;
modify_duration_in_file(file_path, new_duration);
Feel free to ask, if you have any doubt in understanding the code.
I hope this was helpful.
참고 항목
카테고리
Help Center 및 File Exchange에서 File Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!