How to write in a csv file in Mac?

조회 수: 1 (최근 30일)
Faranak
Faranak 2016년 7월 22일
댓글: Walter Roberson 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