How can I open different file types with one skript

1 view (last 30 days)
I want to be able to select a filetype (.txt/.xlsx/.csv/.mat) with one skript. I thought about writing an if/else skript like
[filename,filepath] = uigetfile('','filep');
file = [filepath,filename];
% -- open, read, close .txt file, if exist --
fid = fopen(file);
if fid == -1, error('File could not be found. Check filename and path.'); end
%for .txt
result = isfile('.txt')
if exist (result)
do...
else
result=isfile('.xlsx')
if exist (result)
do...
I'm sure there must be an easy way but no idea how I can write that.. Thanks a lot

Answers (1)

Geoff Hayes
Geoff Hayes on 24 Jul 2018
Edited: Geoff Hayes on 24 Jul 2018
inah - use fileparts to get the file extension which you can then use in your if/elseif conditions. For example,
[filename,filepath] = uigetfile('','filep');
f = fullfile(filepath,filename);
[filepath,name,ext] = fileparts(f);
if strcmpi(ext,'txt')
% text file
elseif strcmpi(ext,'xlsx')
% Excel file
elseif strcmpi(ext,'mat')
% mat file
elseif strcmpi(ext,'csv')
% csv
else
fprintf('unhandled file extension\n');
end
Note how fullfile is used to correctly build f which is the full filename and path.

Community Treasure Hunt

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

Start Hunting!