The os
module in the standard library includes the path sub-module which provides useful functions for working with and manipulating paths.
The isfile()
function in the path
sub-module is used to determine whether a given path is an existing regular file. Typically, a file, has contents stored in it unlike a directory or a link. Normally, files have an extension which is used to determine the type of file, for example Python files usually have a ".py" extension.
To use the isfile()
function, we will first need to import it in our program as follows.
from os.path import isfile
from os.path import isfile
paths = ['images/john.png', 'project/files/tests.py', 'project/static/css/styles.css', 'project/static/js/animations.js']
for p in paths:
print(isfile(p))
p |
The path to be checked. |
The isfile()
function asserts whether the input path represents a file that actually exists, True
if so, False
otherwise. The path can be relative to the current working directory or an absolute path.
from os.path import isfile
paths = ['project/images/john.png', 'project/tests.py', 'project/static/styles.css', 'project/main.py']
for p in paths:
print(isfile(p))
True
True
True
True
In the above example, we tested the isfile()
function with some relative paths. The function returned True because the files existed in the computer the interpreter was run.