Changing a CSV file while keeping it readable by MATLAB

9 次查看(过去 30 天)
I have a CSV file (see attached) that I want to make alterations to, but I want to save it in the same format that it's already in. What I do is open the file using the following code (so that it's applicable to different file types):
A = fopen(x)
raw=fread(A)
fclose(A)
str=char(raw')
This produces a 1-by-n cell array that I can work with. All good, I do my changes, but then I can't save it in the same format. I can't use csvwrite because it's not in matrix format. I can use xlswrite to write it as a new CSV file, but when I use the above code to fopen it, the char conversion produces gibberish, with stuff like " @ þCúíëÀõ? ", even though it's a CSV file and looks similar to the original. How can I change the CSV while keeping it useable so that the fopen-fread-char routine still works? Thanks.
  2 个评论
Stephen23
Stephen23 2018-11-8
编辑:Stephen23 2018-11-8
"...I do my changes, but then I can't save it in the same format"
It sounds like maybe you are changing the file encoding. Please attach one of the altered files which import incorrectly.

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2018-11-9
编辑:Stephen23 2018-11-9
'but then I can't save it in the same format.'
Yes, you can.
'I can't use csvwrite because it's not in matrix format.'
That seems possible.
'I can use xlswrite to write it as a new CSV file, but when I use the above code to fopen it, the char conversion produces gibberish, with stuff like " @ þCúíëÀõ? ", even though it's a CSV file and looks similar to the original.'
Nope. It is certainly not a CSV file. What you created (attached) is actually a binary Excel .xls file with the file extension .csv. So nothing like a CSV text file at all. I just changed the file extension and it opened as a perfect .xls file.
'How can I change the CSV while keeping it useable so that the fopen-fread-char routine still works? Thanks.'
By writing a text file, not a binary .xls file.

更多回答(1 个)

KSSV
KSSV 2018-11-8
[num,txt,T] = xlsread('C:\Users\srinivas\Downloads\Crayford01092018103600.csv') ;
T = readtable('C:\Users\srinivas\Downloads\Crayford01092018103600.csv') ;
Use either xlsread or readtable. Make changes in T, and write into file using xlswrite or writetable.
  2 个评论
Sam Smith
Sam Smith 2018-11-8
编辑:Sam Smith 2018-11-8
Thank you. This is a way of doing it, but is there a way of doing it if I want to do the fopen-fread-char routine? xlsread changes the time to a number which I don't want.
KSSV
KSSV 2018-11-9
You can use xlsread s below:
[num,txt,raw] = xlsread(myfile) ;
Now raw, will have all the data of excel file. No change in the data.

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by