Automatically open new files as they appear in a folder

7 vues (au cours des 30 derniers jours)
Emilie
Emilie le 6 Sep 2021
Commenté : Jan le 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!

Réponse acceptée

Jan
Jan le 6 Sep 2021
Modifié(e) : Jan le 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 commentaires
Emilie
Emilie le 6 Sep 2021
thank you so much, I'll try this out!!
Jan
Jan le 6 Sep 2021
I try it also. If it is working, maybe it is worth to publish it in the FileExchange.

Connectez-vous pour commenter.

Plus de réponses (1)

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

Catégories

En savoir plus sur Software Development Tools dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by