How do I add data to an already existing text file?

10 views (last 30 days)
I have a text file of 35000 lines and two excel files from which I have to input data on two lines and save it in the text files in lines 55 and 65. I have tried breaking down the text file into a matrix of sorts and assigned the values but it is not displaying the updated results on the text file . Please let me know what can be done to get the updated values in the text file.

Answers (1)

Geoff Hayes
Geoff Hayes on 15 Jan 2016
Please describe the contents of the text file (just one column, more, etc.) and show the code that you are using to read the data from this file, how you insert the two new rows, and then how you write the data to the updated file.
A quick example on how to do this is as follows
% create a new file with some dummy data
dummyData = randi(42,16,4);
% write the data to file
fid = fopen('myDummyDataFile.txt','wt');
fprintf(fid,[repmat('%d ',1,size(dummyData,2)) '\n'],dummyData');
fclose(fid);
Now, to read back the data into a matrix do
myDataToModify = load('myDummyDataFile.txt');
Add a new row of events between rows 8 and 9
myDataToModify = [myDataToModify(1:8,:); repmat(7,1,size(myDataToModify,2)); myDataToModify(9:end,:)];
And write to file
% write the data to file
fid = fopen('myDummyDataFile.txt','wt');
fprintf(fid,[repmat('%d ',1,size(myDataToModify,2)) '\n'], myDataToModify');
fclose(fid);
The above is an example only. There are several ways to read and write data to file so please don't limit yourself to just fprintf.

Community Treasure Hunt

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

Start Hunting!