In Python, there are many ways to do so, like using built-in functions or by using Python standard library.
Option 1:-
open() and try...except
- It is a Pythonic way of checking whether a file exists without exception: You simply try to open the file with the built-in open() function:
- If the file exists without exception it will return the message that files found and if the file doesn’t exist then it will raise FileNotFoundError.
Here is an example that tells this technique:-
try:
f = open('abc.txt')
f.close()
except FileNotFoundError:
print('File does not exist')
- Here I am using the close() method on the file object to release the underlying file handle. You should make it practice when dealing with the files in Python.
- If the file is not closed than handling it explicitly, it is difficult to know when exactly the file will be closed automatically by the Python at runtime. This makes your programs run less efficiently.
- open() and a try...except clause has some advantages when it comes to file handling in Python. It can help you avoid bugs caused by file existence race conditions:
Option 2:-
pathlib.Path.exists()
This library is included in Python 3.4 and above version using this module is much easier to handle the exception.
This module provides helper functions for many file system operations, finding out whether a path points to a file or a directory.
To check whether a path points to a valid file you can use the path.exist()method. To find out whether a path is a file, instead of a directory, you’ll want to use path.is_file().
Here is an example:-
import pathlib
path = pathlib.Path('abc.txt')
path.exists()
path.is_file()
pathlib provides us a clear object-oriented interface for working with the files. You are no longer working with str objects representing file paths—but instead, you are handling Path objects with relevant methods and attributes.
To know more about this you can have a look at the following video tutorial:-
Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.