How do I overwrite part of a .tsv file?
4 views (last 30 days)
Show older comments
I need to replace some old data in a .tsv file with new data. I need to keep the first 13 rows of the original file and overwrite the following 40000 rows with 40000 rows of the new data. I have used the following code for this:
dlmwrite('MyFile.tsv',M,'precision','%.6f','delimiter','\t','roffset',13);
, which appends my new data on the original file. However, I cannot find a way of overwriting only part of the original file...'-append' does not seem to work/help.
Any help would be appreciated.
0 Comments
Answers (2)
Image Analyst
on 21 Feb 2023
Try this
data = dlmread(filename); % Get old data.
% Now change ONLY rows 14 and lower.
% Now write back the entire matrix.
dlmwrite('MyFile.tsv', M, 'precision', '%.6f', 'delimiter', '\t');
3 Comments
Image Analyst
on 21 Feb 2023
Personally I'd just use fprintf() to manually write it out line by line.
Walter Roberson
on 21 Feb 2023
dlmwrite always overwrites all of the text file unless -append is used. There is no way to get dlmwrite to overwrite part of a text file.
There is also no way to get writetable or writematrix or writecell to overwrite part of a text file.
The fundamental technical implementation of text files, in all operating systems since Vax VMS RMS, has only permitted overwriting with exactly the same number of characters. (There are also operating system calls to truncate a file, but MATLAB does not provide access to those)
2 Comments
Walter Roberson
on 21 Feb 2023
You can use readcell() and writecell to overwrite the entire file while keeping the identity of the initial lines as text, but there is the danger that the headers might get extra tabs put on the end so that the number of columns matches.
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!