Azzera filtri
Azzera filtri

How to write in a csv file in Mac?

1 visualizzazione (ultimi 30 giorni)
Faranak
Faranak il 22 Lug 2016
Commentato: Walter Roberson il 22 Lug 2016
Hello,
I am trying to write a csv file in mac. My program everytime runs and give 4 value + one name, I want the program write it everytime in next line, but problem is that everytime I run it will write in the same line. I want the program check first empty row and start writing in that row. I couldn't find any way to address specific line with using fprintf. and problem is that by every time using fopen it will create a new file
I used this codes for csv:
fe={nameinfo number AVG MIN MAX}; %%%%this 5 values by everytime running the program changes
names={'name' 'classnum' 'avg' 'min' 'max'}; %%%%it will be the header
fid=fopen('classes.csv','w'); %%%creat a csv file with name of classes
fprintf(fid, '%s,', names{1,1:end}) ; %%%%write the header
fprintf(fid, '\n%s, %f, %f, %f, %f,',fe{1:1:end}); %%%write the name and values

Risposte (1)

Walter Roberson
Walter Roberson il 22 Lug 2016
fid = fopen('classes.csv', 'a'); %append if the file exists, create it if it does not
  2 Commenti
Faranak
Faranak il 22 Lug 2016
Thank you so much, It works. Just one more question. everytime I am running program it write header too, is there any way to ask to write header only one time? or if it wants to write it only write it on first row.
Walter Roberson
Walter Roberson il 22 Lug 2016
You can use exist() to check if a file already exists, and you can use dir() to check its size. If it exists and is non-empty, skip writing the file.
(If you needed to update the header line each time through and the header line was a fixed size, then there would be ways to do that. But if you needed to update the header each time and needed it to be variable size with no maximum size imposed, then you would need to recopy the file each time. You can update text files but only under the circumstance that you do not change the size of any line.)

Accedi per commentare.

Categorie

Scopri di più su Startup and Shutdown in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by