How do I check if a file exists or not, without using the try statement?
You can follow these three ways:
Note1: The
os.path.isfile
used only for files
import os.path
os.path.isfile(filename) # True if file exists
os.path.isfile(dirname) # False if directory exists
Note2: The
os.path.exists
used for both files and directories
import os.path
os.path.exists(filename) # True if file exists
os.path.exists(dirname) #True if directory exists
The
pathlib.Path
method (included in Python 3+, installable with pip for Python 2)
from pathlib import Path
Path(filename).exists()
import os.path
def isReadableFile(file_path, file_name):
full_path = file_path + "/" + file_name
try:
if not os.path.exists(file_path):
print "File path is invalid."
return False
elif not os.path.isfile(full_path):
print "File does not exist."
return False
elif not os.access(full_path, os.R_OK):
print "File cannot be read."
return False
else:
print "File can be read."
return True
except IOError as ex:
print "I/O error({0}): {1}".format(ex.errno, ex.strerror)
except Error as ex:
print "Error({0}): {1}".format(ex.errno, ex.strerror)
return False
#------------------------------------------------------
path = "/usr/khaled/documents/puzzles"
fileName = "puzzle_1.txt"
isReadableFile(path, fileName)
How do I check whether a file exists, without using the try statement?
In 2016, this is still arguably the easiest way to check if both a file exists and if it is a file:
import os
os.path.isfile('./file.txt') # Returns True if exists, else False
isfile
is actually just a helper method that internally uses os.stat
and stat.S_ISREG(mode)
underneath. This os.stat
is a lower-level method that will provide you with detailed information about files, directories, sockets, buffers, and more. More about os.stat here
Note: However, this approach will not lock the file in any way and therefore your code can become vulnerable to "time of check to time of use" (TOCTTOU) bugs.
So raising exceptions is considered to be an acceptable, and Pythonic, approach for flow control in your program. And one should consider handling missing files with IOErrors, rather than if
statements (just an advice).
If you imported NumPy already for other purposes then there is no need to import other libraries like pathlib
, os
, paths
, etc.
import numpy as np
np.DataSource().exists("path/to/your/file")
This will return true or false based on its existence.
In 2016 the best way is still using os.path.isfile
:
>>> os.path.isfile('/path/to/some/file.txt')
Or in Python 3 you can use pathlib
:
import pathlib
path = pathlib.Path('/path/to/some/file.txt')
if path.is_file():
...
You could try this (safer):
try:
# http://effbot.org/zone/python-with-statement.htm
# 'with' is safer to open a file
with open('whatever.txt') as fh:
# Do something with 'fh'
except IOError as e:
print("({})".format(e))
The ouput would be:
([Errno 2] No such file or directory: 'whatever.txt')
Then, depending on the result, your program can just keep running from there or you can code to stop it if you want.