How can I modify the first row(i.e. strings) of an existing csv file without overwriting the rest of data in matlab
7 次查看(过去 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).

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
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.
采纳的回答
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 .
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!