read file in folder with multiple files with similar names

19 ビュー (過去 30 日間)
Ihaveaquest
Ihaveaquest 2022 年 8 月 16 日
コメント済み: Ihaveaquest 2022 年 8 月 22 日
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);

採用された回答

Walter Roberson
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 件のコメント
Ihaveaquest
Ihaveaquest 2022 年 8 月 22 日
Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Find more on Dates and Time in Help Center and File Exchange

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by