How to overwrite existing text file without saving as new file
30 views (last 30 days)
Show older comments
I am trying to overwrite the last line in a text file and save it. I don't want to write to a new file as the name needs to be the same before and after. Unfortunately, I can't just append text to the file, because the last line of the file before editing has to change. Thanks!
0 Comments
Answers (3)
Walter Roberson
on 13 Oct 2023
The easiest approach in MATLAB is to read the entire file, change the last line, and write out the result to the original file name.
This has a bit of risk in that if something goes wrong during the writing, then you could end up with a file that is incomplete.
You might think that surely there must be a way to only change the last line. Unfortunately, the way that text files are structured in any operating system you are likely to ever use, the operating system is not keeping track of where the line boundaries are, and the best you can do is use line reading and file information operations to start at the beginning of the file and progress a line at a time figuring out where the lines are, then tell the file system to move you back to the beginning of the last line (based on the information about position that you recorded) and then tell it to write a line from there. Once you have written the new line, if it was at least as long as the old line, you are fine -- but if it was shorter than the previous line so that the overall file would be shorter, you have a problem. Windows and Linux and MacOS all define internal calls to allow you to "truncate" a file at the current position, but MATLAB does not provide any interface to such a function so you are stuck (and need to do something like write blanks to where the file used to end.) This all is a nuisance, so doing operations "in-place" in a file is usually only done for binary files, and for text files you typically end up reading everything, clobbering the old file, then writing all of the updated information.
0 Comments
Sulaymon Eshkabilov
on 13 Oct 2023
If understood correctly, use 'append' option with writematrix():
M = magic(5);
writematrix(M,'MN.txt')
N = M+2;
writematrix(N,'MN.txt','WriteMode','append')
type MN.txt
% ALt. way is using dlmwrite() which is not recommended though!
M = magic(5);
dlmwrite('MN2.txt',M,'delimiter',' ','roffset',1)
N = M+2;
dlmwrite('MN2.txt',N,'-append','delimiter',' ','roffset',1)
type MN2.txt
0 Comments
Florian Bidaud
on 13 Oct 2023
Edited: Florian Bidaud
on 13 Oct 2023
Hi,
Might not be the fastest to do but it should work:
text_file = 'text.txt';
text_data = readcell(text_file);
text_data{end} = 'your new line replacing the last one';
writecell(text_data,text_file);
0 Comments
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!