In Python, you can check whether a file exists without raising any exceptions by using the os.path
module. The os.path
module provides several functions for working with file paths, including the exists()
function, which returns True
if a file exists at the given path, and False
otherwise.
Here’s an example of how to use the os.path.exists()
function to check if a file exists:
import os
file_path = ‘/path/to/file.txt’
if os.path.exists(file_path):
print(‘File exists’)
else:
print(‘File does not exist’)
In this example, we first import the os
module, and then define the path to the file we want to check in the file_path
variable. We then use the os.path.exists()
function to check if the file exists at the given path. If it does, we print a message saying that the file exists. If it doesn’t, we print a message saying that the file does not exist.
Using this method, you can check for the existence of a file in Python without raising any exceptions.
- sunny asked 1 month ago
- You must login to post comments
Please login first to submit.