How can I modify the first row(i.e. strings) of an existing csv file without overwriting the rest of data in matlab

10 vues (au cours des 30 derniers jours)
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).
Capture.PNG
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 commentaires
Stephen23
Stephen23 le 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.
Jialun Zhang
Jialun Zhang le 29 Nov 2018
@Stephen Cobeldick: Ok that makes sense. Thanks a lot for your answer!

Connectez-vous pour commenter.

Réponse acceptée

Walter Roberson
Walter Roberson le 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 .
  1 commentaire
Jialun Zhang
Jialun Zhang le 29 Nov 2018
Yeah I also thought about using cell array to store the data which might potentially solve this problem. Thanks anyway!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Tags

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by