Automatically open new files as they appear in a folder

7 Ansichten (letzte 30 Tage)
Emilie
Emilie am 6 Sep. 2021
Kommentiert: Jan am 6 Sep. 2021
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!

Akzeptierte Antwort

Jan
Jan am 6 Sep. 2021
Bearbeitet: Jan am 6 Sep. 2021
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 Kommentare
Emilie
Emilie am 6 Sep. 2021
thank you so much, I'll try this out!!
Jan
Jan am 6 Sep. 2021
I try it also. If it is working, maybe it is worth to publish it in the FileExchange.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Yongjian Feng
Yongjian Feng am 6 Sep. 2021
Implement a background thread that scans the folder?

Kategorien

Mehr zu Software Development Tools finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by