Automatically open new files as they appear in a folder

조회 수: 7 (최근 30일)
Emilie
Emilie 2021년 9월 6일
댓글: Jan 2021년 9월 6일
Hi!
I am currently using the importdata function to import data from a specific file input that I have to change, everytime I have a new file.
I am wondering if there's a function that would automatically detect a new .csv file and import it in Matlab?
Thanks in advance!

채택된 답변

Jan
Jan 2021년 9월 6일
편집: Jan 2021년 9월 6일
Under Windows this canbe done by .NET using a System.IO.FileSystemWatcher. But in general a simple timer is easier:
% [UNTESTED CODE]
function Observer = ObserveFolder(Pattern, Fcn)
Observer = timer('BusyMode', 'queue', ...
'ExecutionMode', 'fixedSpacing', ...
'Period', 5, ... % Number of seconds between checks
'TimerFcn', @(H, E) CheckFolder(H, E, Pattern, Fcn), ...
'UserData', [], ...
'DeleteFcn', @(H, E) disp('Observer stopped.'));
start(Observer);
end
function CheckFolder(TimerH, EventData, Pattern, Fcn)
newList = dir(Pattern);
FileList = fullfile({newList.folder}, {newList.name});
DateList = {newList.date};
oldKey = TimerH.UserData;
if isempty(oldKey)
newFile = FileList;
else
key = strcat(FileList, '?', DateList);
newFile = FileList(~ismember(key, oldKey));
oldKey = key;
end
for iFile = 1:numel(newFile)
Fcn(newFile{iFile});
end
end
Call this as:
Fcn = @(File) disp(File); % A dummy function
Obs = ObserveFolder(fullfile(Folder, '*.csv'));
... let it work and stop if by:
delete(Obs)
  댓글 수: 2
Emilie
Emilie 2021년 9월 6일
thank you so much, I'll try this out!!
Jan
Jan 2021년 9월 6일
I try it also. If it is working, maybe it is worth to publish it in the FileExchange.

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

추가 답변 (1개)

Yongjian Feng
Yongjian Feng 2021년 9월 6일
Implement a background thread that scans the folder?

카테고리

Help CenterFile Exchange에서 Software Development Tools에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by