Effacer les filtres
Effacer les filtres

Reading files with different extension from directory

34 vues (au cours des 30 derniers jours)
Jiayun Liu
Jiayun Liu le 12 Oct 2022
Commenté : dpb le 12 Oct 2022
Currently I am reading files from a directory using "fullName = dir([path '*.tif'])" to find all files with the .tif extension. If the folder contains .png files instead, I have to change the code to "fullName = dir([path '*.png'])". Is there a way to do this without changing the code i.e. is there a way to read the image file from a folder that contains either .png or .tif files without changing the code?

Réponse acceptée

dpb
dpb le 12 Oct 2022
The MATLAB builtin dir() function doesn't have the facility to handle multiple extensions in a single call; there are a couple of ways to approach it
  1. dir() of the subdirectory of interest for all files and then select those for which the file extension is one of your select list. This entails returning fileparts of the dir() struct to be able to scan the extensions directly to avoid the possible matching of some substring in the file name.
  2. Make multiple calls to dir() with each of the desired file extensions in turn and combine the resulting structures to get the overall.
There are various perturbations about the above, but that's the basic choice without using direct calls to the OS which may have more extension features available.
  7 commentaires
Jiayun Liu
Jiayun Liu le 12 Oct 2022
I see. Thank you
dpb
dpb le 12 Oct 2022
Just for rounding out...
1.
EXT={'.tif','.png'}; % the list of extensions wanted
D=dir(fullfile(P,'*.*')); % directory of the path with all extensions
[~,~,e]=fileparts({D.name}); % the list of extensions found
D=D(matches(e,EXT,"IgnoreCase",1)); % save the matches
In the end, it's probably easier to just suffer the overhead of the multiple calls for just a couple in the list; if the list grows significantly it might be better to do something like this. In this case one only modifies the one data list of possible extensions; in the other have to keep adding lines of code.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur File Operations dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by