Coding Triumph

Helpful code snippets & tutorials

How to check whether a path is a file or a directory in Python

In this post, you shall learn if a given path is a file or a directory with the help of the Python programming language.

Prerequisite:

  1. Python version 3
  2. isfile() and isdir() methods from the os .path module

Methods definition:

# isfile() method
os.path.isfile(path)
# "path": the file path.
# returns True if "path" is an existing regular file.

# isdir() method
os.path.isdir(path)
# "path": the directory path.
# returns True if "path" is an existing directory.

The script:

import os

file = '/home/User/Desktop/test.txt'
dir = '/home/User/Desktop/'

isFile = os.path.isfile(file)
print(isFile) # True
isFile = os.path.isfile(dir)
print(isFile) # False

isDir = os.path.isdir(dir)
print(isDir) # True
isDir = os.path.isdir(file);
print(isDir) # False
If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments