How can I modify the first row(i.e. strings) of an existing csv file without overwriting the rest of data in matlab
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Jialun Zhang
am 26 Nov. 2018
Kommentiert: Jialun Zhang
am 29 Nov. 2018
Hello ,
I am trying to modify a particular cell("PMW") of an existing csv file to "P (MW)"and keep the rest of the content intact. The first row consists of name tags for the rest rows of the csv file. I have used fopen() in rt+ permission argument to avoid discarding the rest of the contents in the csv file. The code looks like this
Prewrite = strcat('P',{' '},'(MW)');
fid = fopen('xxx.csv');
lineex = fgetl(fid);
lineex = replace(lineex,"PMW",Prewrite);
fclose('all');
fid = fopen('xxx.csv','rt+');
fprintf(fid,'%s\n',lineex);
fclose('all');
However, the resulting csv file has overwritten the first column of the second row; three char characters are mssing for the B1 cell("ROL2" in the screenshot below while it should be SAIROL2).

I am not sure if this is due to the fact that fprintf will overwirte the exisitng data when using \n new line operator. If so how can I fix this issue to maintain its original content?
4 Kommentare
Stephen23
am 27 Nov. 2018
@Jialun Zhang: changing some characters in the middle of a text file without changing the rest of the file data is only possible if you overwrite exactly the same number of characters. It is not possible to insert extra characters (as you are trying to do) without overwriting something. If you want extra characters you will have to rewrite the whole file.
This is because text files are stored simply as a sequence of characters. If you want to insert characters in the middle, the the rest of the characters all have to get shifted along.
Akzeptierte Antwort
Walter Roberson
am 27 Nov. 2018
Use MS Windows with Excel installed and xlswrite to the csv file passing in the range to overwrite .
There might also be some approaches using readtable and writetable.
Every approach will rewrite to end of file because as explained the content needs to be shifted to make room. The xlswrite approach takes care of the details for you .
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!