Automatically open new files as they appear in a folder

7 visualizaciones (últimos 30 días)
Emilie
Emilie el 6 de Sept. de 2021
Comentada: Jan el 6 de Sept. de 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!

Respuesta aceptada

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

Iniciar sesión para comentar.

Más respuestas (1)

Yongjian Feng
Yongjian Feng el 6 de Sept. de 2021
Implement a background thread that scans the folder?

Categorías

Más información sobre Software Development Tools en Help Center y File Exchange.

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by