xxxxxxxxxx
import os
os.path.exists("file.txt") # Or folder, will return true or false
xxxxxxxxxx
#using pathlib
from pathlib import Path
file_name = Path("file.txt")
if file_name.exists():
print("exists")
else:
print("does not exist")
xxxxxxxxxx
# 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/
xxxxxxxxxx
def open_file(path):
try:
# data = pathlib.Path(path).read_text() # alternative for the following two lines
with open(path, encoding='utf-8') as f:
data = f.read()
# handle data
except FileNotFoundError:
# handle exception
return
# or if you only care about whether the path exists or not
os.path.isfile(path) # is file
os.path.isdir(path) # is dir
os.path.exists(path) # is file or dir
xxxxxxxxxx
from pathlib import Path
path_to_file = 'readme.txt'
path = Path(path_to_file)
if path.is_file():
print(f'The file {path_to_file} exists')
else:
print(f'The file {path_to_file} does not exist')
Code language: PHP (php)