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

10 ビュー (過去 30 日間)
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 件のコメント
Stephen23
Stephen23 2018 年 11 月 27 日
@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 2018 年 11 月 29 日
@Stephen Cobeldick: Ok that makes sense. Thanks a lot for your answer!

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2018 年 11 月 27 日
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 件のコメント
Jialun Zhang
Jialun Zhang 2018 年 11 月 29 日
Yeah I also thought about using cell array to store the data which might potentially solve this problem. Thanks anyway!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by