How to write in a csv file in Mac?

1 次查看(过去 30 天)
Faranak
Faranak 2016-7-22
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

回答(1 个)

Walter Roberson
Walter Roberson 2016-7-22
fid = fopen('classes.csv', 'a'); %append if the file exists, create it if it does not
  2 个评论
Faranak
Faranak 2016-7-22
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 2016-7-22
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.)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by