read file in folder with multiple files with similar names
조회 수: 2 (최근 30일)
이전 댓글 표시
file_name = dir('*.rpt*');
------------------
some where in here would like code that picks the file with latest data
file name 'data_20220804_0211.rpt'
-----------------------------
file = fopen(file_name.name, 'r');
L = textscan(fileID,'%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s');
report_size = size(L);
댓글 수: 0
채택된 답변
Walter Roberson
2022년 8월 17일
In the restricted case that the files are being generated dynamically, then
dinfo = dir('*.rpt*');
[~,newest_idx] = max(datetime({dinfo.date}))
newest_filename = dinfo(newest_idx).name;
What this is doing is looking at the modification date information recorded for each of the files, and picking out the newest one.
In the case where the files might have been sitting around for a while, or might have been transferred between directories, then the modification date becomes less reliable, and you have to start processing the date information
dinfo = dir('*.rpt*');
rawnames = {dinfo.name};
datenames = regexprep(rawnames, '^.*_(\d{8})_(\d{4})\..*$', '$1 $2');
%any name that is not exactly 13 characters is a name that did not follow
%the pattern and we cannot parse.
mask = cellfun(@length, datenames) == 13;
rawnames = rawnames(mask);
datenames = datenames(mask);
filetimes = datetime(datenames);
[~, maxidx] = max(filetimes);
newest_filename = rawnames{maxidx};
댓글 수: 5
Walter Roberson
2022년 8월 18일
It turns out that in POSIX, file modification times are recorded as time_t which is (full) seconds since a particular time. So resolution down to one second is all that you can get from a file timestamp. Both datetime() and serial date number are able to resolve down to 1 second without problem.
It is potentially possible that the datenum version might vary by about 10 microseconds from the datetime version.
It is possible that the two might differ in interpretation of leap seconds.
It is possible that the two might differ about timezone when formatted.
It is possible that the two might differ about daylight time when formatted.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!