When working with Python, you may only need to perform certain actions when a file or directory exists.
You can check if a file exists using the file.exists() method in Python.
In this tutorial, you will learn about the different methods available to check if a file exists in Python.
if you are in a hurry
You can use the following code snippet to do thischeck whether the file exists without exception.
- If the file exists and is readable, then you will see theThe file existsMessage.
- If the file does not exist or cannot be read, you will see theThe file does not existMessage.
import pathlibfile = pathlib.Path("C:/temp/Test_Folder/test.txt")if file.exists(): print ("El archivo existe")else: print ("El archivo existe")
The file exists, so you see the following output.
Production
The file exists
If you want to understand the details, read on...
You will learn about the different methods available to check if a file exists in Python.
There are three libraries available in Python to check if a file exists.
- Using the operating system module
- With pathlib
- use balloon
Table of contents
Use the OS module to check if the file exists
You can check if a file exists by using theexists()
method available in theos.ruta
Module. Ask themexist() doc.
Isexists()
The method accepts the file path parameter, which must be checked for its existence.
Where from,
absolute path
– If you want to check whether a file exists in another directory.
Öfilename
– If you want to check the file in the current directory.
Returns,
RIGHT
– If the file exists and is readableNOT CORRECT
– If the file does not existÖunreadable The following example shows how to check whether the filetexto.txt
consists in thec:/temp/test_folder/
.
Rest
desde os import pathpath.exists("C:/temp/Test_Folder/test.txt")
Since the file exists in the directory, you see the outputRIGHT
Production
RIGHT
So you can check if a file exists by using theoperating system.route
Module.
Use pathlib to check if the file exists
Pathib
will be introduced in Python 3.4. It is the most intuitive library for interacting with the file system. You can use this method to check whether a file exists without exception.
You can installPathib
with the following snippet.
Installation
pip install pathlib
you can use the...Away
class in thePathib
Module to create a route object. Use ofAway
class you can use theexists()
Method to check if the path exists.
Camino
The class accepts the file path information.
Where from,
absolute path
– If you want to check whether a file exists in another directory.
Öfilename
– If you want to check the file in the current directory.
Use the following snippet to verify that the file exists by using theRutalib
Module.
Rest
import pathlibfile = pathlib.Path("C:/temp/Test_Folder/test.txt")if file.exists(): print ("El archivo existe")else: print ("El archivo existe")
if the file existsjis legible, then theexists()
the method returnsRIGHT
. Therefore, the if statement is executed.
Production
The file exists
Fragment 2
import pathlibfile = pathlib.Path("C:/temp/Test_Folder/test_1.txt")if file.exists(): print ("El archivo existe") else: print ("El archivo existe")
If the file does not exist or cannot be read, theexists()
the method returnsRIGHT
. therefore, themore
the statement is executed.
Production
The file does not exist
Here's how you can use themRutalib
Module to check if the file exists.
Use Glob to check if the file exists
IsGlobal ModuleIn Python, you can access the file system.
The main benefit of usingGlobus
Modulo is pattern matching. You can also use this method to check if a file exists without using exceptions.
To check if the file exists, use theGlobus ()
Method available in the global module.
Accepts the file path information.
Where from,
absolute path
– If you want to check whether a file exists in another directory.
Öfilename
– If you want to check the file in the current directory.
Returns
RIGHT
– If the file existsjreadableNOT CORRECT
– If the file does not existÖit cannot be read
Use:If heglob.glob
is used outsideAND
, a list of files matching the passed condition is returned.
Rest
import globif glob.glob("C:/temp/Test_Folder/test.txt"): print ("Existe un archivo")
Production
The file exists
This is how you can use the glob module to check whether a file exists.
You learned about the different methods available to check if a file exists in Python.
Check if a hidden file exists
You can check if the hidden file exists by typing theglob.glob
module or thatos.ruta
Module. Both methods are shown below.
It is similar to checking regular files. Only the files are hidden.
Fragment with glob
import globif glob.glob("C:/temp/Test_Folder/hidden_file.txt"): print ("El archivo existe")
To test on Windows, we hide the file on Windows and run the above script. We saw the next exit. therefore the sameGlobus
The module can be used to check whether the hidden file exists or not.
Production
The file exists
Fragment with os.path
Use theexists()
method available in theos.ruta
Module to check if the hidden file exists.
from os import pathpath.exists("C:/temp/Test_Folder/hidden_file.txt")
Production
RIGHT
This is how you can check if a hidden file exists.
Check if the list contains multiple files
This section shows you how to check if multiple files exist in a specific directory.
You create a list of files.
You can use the list comprehension to verify that the file containing the existsos.ruta.isfile(f)
.
Returns a new list where contains
RIGHT
– Whether the file exists.NOT CORRECT
– If the file does not exist.
So you can use thoseat
Function to check if all iterables are presentRIGHT
.
All functions return
RIGHT
– If all are iterablesRIGHT
on the listNOT CORRECT
– If at least one iterable inNOT CORRECT
on the list. This means that at least one file does not exist.
Rest
An example where all files are present.
import osfilelist = ['C:/temp/Test_Folder/file1.txt', 'C:/temp/Test_Folder/file2.txt', 'C:/temp/Test_Folder/test.txt']if all([os.path .isfile(f) für f in Dateiliste]): print("Todos los archivos existen") else: print("Todos los archivos existen")
Production
all files exist
Fragment 2
An example where at least one file does not exist.
import osfilelist = ['C:/temp/Test_Folder/file3.txt', 'C:/temp/Test_Folder/file2.txt', 'C:/temp/Test_Folder/test.txt']if all([os.path .isfile(f) für f in Dateiliste]): print("Todos los archivos existen") else: print("Todos los archivos existen")
Production
All files do not exist
So you can check whether there are multiple files in the list or not.
Verify that the regular expression file exists
In this section, you will check if files exist by checking theregular sentenceor pattern.
It is also known as checking if a file exists using wildcards.
As seen before, for theFile access operation with pattern matching, you needUse the global module.
Use the following snippet to verify that the file starts with the nameoffice hoursexists in the directory.
Rest
import globif glob.glob('C:/temp/Test_Folder/file*.txt'): print("File exists with initial string file")
andat least one text file existsin the directory starting with textoffice hours
, then you will see the following output.
Production
The file exists with the start string file
This is how you can use the regular expression to check if a file exists.
Check if the file exists in the subdirectory
To check if a file exists in the subdirectory, you can directly use the subdirectory information along with the file name as shown below.
The path.exists() method returns
RIGHT
– If the file existsNOT CORRECT
– If the file does not exist in the subdirectory
Rest
vom Betriebssystem import pathpath.exists ("temp/temp.txt")
Production
RIGHT
So you can check if the file exists in the subdirectory.
Check if the file with the extension exists
To check if a file has a specific extension, you can use the regular expression withGlobus
.
This is useful when you want to check if a file type exists in the directory.
Use the*.html
if you want to check if an HTML file exists in the directory.
Rest
import globif glob.glob('*.html'): print("HTML file exists")
Production
HTML file exists
This is how you can check if a specific file type exists in the directory.
Conclusion
In summary, you learned about the different methods available in Python to check if a file exists. You also learned how to use the different methods in different use cases to verify the existence of the file in different scenarios.
If you have any questions, please comment below.
You may also like
- How to list files in a directory in Python?
- How to read binaries in Python?
- How to read a file line by line in Python?