In Python, there are many ways to do so, like using built-in functions or by using Python standard library.
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:-
f = open('abc.txt')
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:
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:-
path = pathlib.Path('abc.txt')
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:-