MATLAB Answers

How can I open different file types with one skript

2 views (last 30 days)
inah on 24 Jul 2018
Commented: inah on 26 Jul 2018
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)
if exist (result)
I'm sure there must be an easy way but no idea how I can write that.. Thanks a lot


Sign in to comment.

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
fprintf('unhandled file extension\n');
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!