exists() and is_file() methods of 'Path' object can be used for checking if a given path exists and is a file.
Python 3 program to check if a file exists:
# File name: check-if-file-exists.pyfrom pathlib import PathfilePath = Path(input("Enter path of the file to be found: "))if filePath.exists() and filePath.is_file(): print("Success: File exists")else: print("Error: File does not exist")
Output:
$ python3 check-if-file-exists.py
Enter path of the file to be found: /Users/macuser1/stack-overflow/index.html
Success: File exists
$ python3 check-if-file-exists.py
Enter path of the file to be found: hghjg jghj
Error: File does not exist