xxxxxxxxxx
File file = new File(fileName);
boolean fileExist = file.exists();
boolean dirExist = file.isDirectory();
if(fileExist && !dirExist)
System.out.println("File Exists and it's not a directory!");
xxxxxxxxxx
>>> 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")
xxxxxxxxxx
# check if file exists
from os.path import exists
file_exists = exists("/content/sample_data/california_housing_test.csv")
print(file_exists)
#True
from pathlib import Path
path = Path("/content/sample_data/california_housing_test.csv")
path.is_file()
#False
xxxxxxxxxx
# Brute force with a try-except block (Python 3+)
try:
with open('/path/to/file', 'r') as fh:
pass
except FileNotFoundError:
pass
# Leverage the OS package (possible race condition)
import os
exists = os.path.isfile('/path/to/file')
# Wrap the path in an object for enhanced functionality
from pathlib import Path
config = Path('/path/to/file')
if config.is_file():
pass
xxxxxxxxxx
<SERVER>
// Open a log file
var myLog = new File("/data/logs/today.log");
// See if the file exists
if(myLog.exists()){
write('The file exists');
}else{
write('The file does not exist');
}
</SERVER>