MATLAB: Check if a file exists

text file

I'm using the "importdata" function to import data from a text file. I would like to have a way to check if the text file exists before attempting to import data from the file. If the file doesn't exist, I would then like to display a custom error message. What is the function that I should use?

Best Answer

Starting in R2017b, you can use the "isfile" function to check if a file exists. For example:
if isfile(filename)
% File exists.

else
% File does not exist.

end
The "isfile" function searches for files only on the specified path or in the current folder.
For R2017a and previous releases, use the "exist" function. For example:
if exist(filename, 'file') == 2
% File exists.
else
% File does not exist.
end
Be sure to specify an absolute path for the file name. The "exist" function searches all files and folders on the search path, which can lead to unexpected results if multiple files with the same name exist.