In Python, you can use the os.path.isfile()
function to check if a file exists. The os.path.isfile()
function takes a file path as its argument and returns True
if the file exists and is a regular file, and False
otherwise.
Here’s an example:
import os.path
file_path = '/path/to/file.txt'
if os.path.isfile(file_path):
print(f'{file_path} exists and is a file.')
else:
print(f'{file_path} does not exist or is not a file.')
In this example, file_path
is the path to the file you want to check. If the file exists and is a regular file, the first print
statement is executed and outputs a message indicating that the file exists and is a file. If the file does not exist or is not a regular file, the second print
statement is executed and outputs a message indicating that the file does not exist or is not a file.