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?

 Akzeptierte Antwort

Jan
Jan am 13 Nov. 2024
Bearbeitet: MathWorks Support Team am 13 Nov. 2024

64 Stimmen

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.

8 Kommentare

shuchita bahadur
shuchita bahadur am 6 Jan. 2017
thanks, works
Muhammad Asad
Muhammad Asad am 29 Jan. 2019
It is mentioned that
"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."
Can you please elaborate with example
sesilia maidelin
sesilia maidelin am 21 Jul. 2021
hi there, how can i use isfile to search if a file with a particular extension exist in my folder? or should i use another folder? thanks!
Jan
Jan am 21 Jul. 2021
@sesilia maidelin: This is a job for the dir command:
FileList = dir(fullfile(yourFolder, '*.jpg'))
This gives you a list of jpg files in the folder.
sesilia maidelin
sesilia maidelin am 22 Jul. 2021
hi there, thanks for replying @Jan , in my case i just want to know the existence of a particular file type in a folder, then move the folder to another parentfolder named complete. so if the folder AAA contains a .txt and .jpgs, i want to move AAA into the folder complete that contains folder AAZ, BBA, etc that also contain .txt and .jpg files. i attached the picture of how the source file look like. I want to move files like 00000715 to the folder complete. Thank you!
Jan
Jan am 13 Dez. 2025
I'd like to edit my answer for a nicer formattig. Unfortunately there is no button for editing. As "editor" I'm able to edit the comments of others, but I cannot modify my own answer. How confusing.
I've been away from this forum for some time.
Walter Roberson
Walter Roberson am 13 Dez. 2025
When @MathWorks Support Team edited your posting, it became internally owned by them, and became something that non-staff are not able to edit.
Jan
Jan am 14 Jan. 2026
Thanks for the explanation. Then I'm wondering, why the Support Team made my answer such ugly. This does not seam smart. Readers will think, that I am an idiot, who does not care about readability. What a pity.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (6)

Image Analyst
Image Analyst am 29 Sep. 2012

10 Stimmen

if exist(fullFileName, 'file')
% File exists. Do stuff....
else
% File does not exist.
warningMessage = sprintf('Warning: file does not exist:\n%s', fullFileName);
uiwait(msgbox(warningMessage));
end

3 Kommentare

Valentino
Valentino am 27 Apr. 2015
Works perfect, thanks!
Nelson dos Santos Netto
Nelson dos Santos Netto am 4 Mär. 2016
Thanks for the information! Btw, I was wondering if this check is purely done regarding the file name or the content in the file itself...The thing is:I'm trying to develop a script to regularly copy files from a sourcefolder to a destinationfolder, but I wanted to make sure I copy only the most recent and modified data, in order to get a more efficient and quicker programme. Could you help me out, please?? Tks a lot!
Image Analyst
Image Analyst am 4 Mär. 2016
It checks if a file with that filename is there. It does not check what the contents are, or even if there are contents. It's possible to have a file with zero bytes. You can use fileInfo = dir(filename) to check size.

Melden Sie sich an, um zu kommentieren.

Azzi Abdelmalek
Azzi Abdelmalek am 29 Sep. 2012
Bearbeitet: Azzi Abdelmalek am 29 Sep. 2012

4 Stimmen

a=dir % or a=dir('folder')
b=struct2cell(a)
any(ismember(b(1,:),'filename.txt'))

2 Kommentare

goc3
goc3 am 6 Mai 2019
I prefer this answer, as it only checks in the current directory.
Jan
Jan am 6 Mai 2019
Bearbeitet: Jan am 6 Mai 2019
But if the current directory contains a huge number of files, it is a waste of time. If the current folder is in a network drive, the slow down is substantial. This is more efficient:
isfile(fullfile(cd, 'filename.txt'))
And if it is unknown, if the file contains a path or not, use https://www.mathworks.com/matlabcentral/fileexchange/28249-getfullpath

Melden Sie sich an, um zu kommentieren.

José-Luis
José-Luis am 29 Sep. 2012
Bearbeitet: José-Luis am 29 Sep. 2012

2 Stimmen

doc exist
Simon
Simon am 2 Nov. 2016
Bearbeitet: Simon am 2 Nov. 2016

2 Stimmen

A more modern / more succinct approach:
assert( exist( filename, 'file ) == 2, 'File not found.' );
Assert is a wonderful thing, and makes error-catching code a lot more compact than lots of if blocks! The way it works is,
assert( condition, error );
where condition is something that returns a logical true or false, and error is the message that results if it's false.

2 Kommentare

Miguel Diaz
Miguel Diaz am 17 Nov. 2016
This is a very nice solution. Except exist(filename,'file') == 2 would occur when the file DOES exist. so a corrected version of this would be:
assert(exist(filename,'file') ~= 2, 'File not found.' );
Overall, nice solution my friend!
Image Analyst
Image Analyst am 17 Nov. 2016
Though a friendlier more informative error message (like in my answer) would be an improvement.
But you're not totally correct. Like you said "exist(filename,'file') == 2 would occur when the file DOES exist." and exist(filename,'file') == 2 would be FALSE when the file DOES NOT exist. Since assert only spits out the error message when the file does not exist (the condition is false), it was correct as Simon originally had it, not your "correction".
Remember, in summary, if the file does exist, the condition is true, and the 'File not found.' message is not printed to the command window. If the file does NOT exist, the condition is false, and so the 'File not found.' message is printed to the command window.

Melden Sie sich an, um zu kommentieren.

ABHAY K K
ABHAY K K am 4 Feb. 2019

0 Stimmen

is there a way to check the files exists in a particular directory without using the filename, What i mean to say is the more generalised way to find out

2 Kommentare

Mahmoud Salah
Mahmoud Salah am 11 Okt. 2020
you can use a function called isfile and can be used as followed
if isfile(filename)==1
else
end
Image Analyst
Image Analyst am 11 Okt. 2020
No. If you don't know the filename(s), you cannot determine if a file exists. The best you could do is to see if ANY files exist in the folder by using the dir() function.

Melden Sie sich an, um zu kommentieren.

donier vask
donier vask am 2 Mai 2022

0 Stimmen

If you are using Python 3 with pathlib you can access os.stat() information using the Path.stat() method, which has the attribute st_size (file size in bytes) can use to check whether python file exists and is not empty,
>>> import os
>>> os.stat("file").st_size == 0
True
But, the stat() method will throw an exception if the file does not exist. The following function will return True/False without throwing (simpler but less robust):
import os
def is_non_zero_file(fpath):
return os.path.isfile(fpath) and os.path.getsize(fpath) > 0

Kategorien

Tags

Noch keine Tags eingegeben.

Gefragt:

am 29 Sep. 2012

Kommentiert:

Jan
am 14 Jan. 2026

Community Treasure Hunt

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

Start Hunting!

Translated by