Quantcast
Channel: How do I check whether a file exists without exceptions? - Stack Overflow
Viewing all articles
Browse latest Browse all 46

Answer by Gopinath for How do I check whether a file exists without exceptions?

$
0
0

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


Viewing all articles
Browse latest Browse all 46

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>