check if a file exists code example
Example 1: how to check whether file exists in python
import os.path
if os.path.isfile('filename.txt'):
print ("File exist")
else:
print ("File not exist")
Example 2: how to check if a file exists in python
# Python program to explain os.path.exists() method
# importing os module
import os
# Specify path
path = '/usr/local/bin/'
# Check whether the specified
# path exists or not
isExist = os.path.exists(path)
print(isExist)
# Specify path
path = '/home/User/Desktop/file.txt'
# Check whether the specified
# path exists or not
isExist = os.path.exists(path)
print(isExist)
# credit to geeksforgeeks.com at
# https://www.geeksforgeeks.org/python-check-if-a-file-or-directory-exists/
Example 3: check if a file exists
>>> import os
>>> os.path.isfile("d:\\Package1\\package1\\fibo.py")
True
>>> os.path.isfile("d:/Package1/package1/fibo.py")
True
>>> os.path.isfile("d:\\nonexisting.txt")
Example 4: if file exist
file_exists ( string $filename ) : bool