필터 지우기
필터 지우기

Reading files with different extension from directory

조회 수: 34 (최근 30일)
Jiayun Liu
Jiayun Liu 2022년 10월 12일
댓글: dpb 2022년 10월 12일
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?

채택된 답변

dpb
dpb 2022년 10월 12일
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
Jiayun Liu
Jiayun Liu 2022년 10월 12일
I see. Thank you
dpb
dpb 2022년 10월 12일
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.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by