How to write in a csv file in Mac?
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
Walter Roberson
2016-7-22
fid = fopen('classes.csv', 'a'); %append if the file exists, create it if it does not
2 个评论
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 Center 和 File Exchange 中查找有关 File Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!