fprintf file timestamp to csv

조회 수: 2 (최근 30일)
Tammy Chen
Tammy Chen 2016년 9월 12일
댓글: dpb 2016년 9월 16일
Hi All, I have a directory with unknown number of text files.
fid = dir('*.txt');
How do I fprintf the timestamps (file.date) of all of these files to a csv file? I tried using the datestr() function,datetime(),cell2mat(), brackets {} and [], & cell2str() functions but they don't work and generate errors when I tried to fprinf it to the csv.
Any pointers would help.
Thanks,

채택된 답변

dpb
dpb 2016년 9월 12일
편집: dpb 2016년 9월 12일
fid isn't good variable name for a directory list; too much associated with a file handle.
d=dir('*.txt'); % the directory structure
fid=fopen('file.date','w'); % open an output file
cellfun(@(s) fprintf(fid,'"%s"\n',s),cellstr(char(d.date))) % and write them out quote-delimited
fid=fclose(fid); % done--close file
  댓글 수: 2
Tammy Chen
Tammy Chen 2016년 9월 13일
Thanks! I was able to incorporate this line into another series of loops so I can print the timestamp out with other stats and file info I need from the data.
cellfun(@(s) fprintf(fid,'"%s"\n',s),cellstr(char(d.date)))
Several questions though, 1. Why do I need to use the cell function for fprintf the "s"? 2. What makes datetime special that it has to be quote delimited in order to be printed as a string? Sorry if my question doesn't make any sense, since I'm still a novice in cell-handling.
Walter Roberson
Walter Roberson 2016년 9월 13일
You do not need to use a cellfun to handle the printing: the solution I gave using a temporary variable handles the task without using cellfun.
The timestamps include characters such as '-' and ':' and spaces that are not valid numbers. The format for csv files requires that strings in csv files be enclosed in double-quotes. The double-quotes being used there are not for the purpose of getting MATLAB to emit strings: they are there to get MATLAB to emit strings that are properly-formatted csv

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2016년 9월 13일
d = dir('*.txt');
dates = {d.date};
fid = fopen('file.csv', 'wt');
fprintf(fid, '"%s"\n', dates{:});
fclose(fid);
No loop is needed.
  댓글 수: 19
Walter Roberson
Walter Roberson 2016년 9월 16일
They are not fixed length.
dpb
dpb 2016년 9월 16일
I had presumed not; wondered, though, about an array then...guess they're more classes/objects overhead to deal with, then. At this stage of the game I wonder why also but would likely have been preference over the cellstr route they took first...

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by