w3resource

Python: Check whether a file path is a file or a directory

Python Basic: Exercise-85 with Solution

Write a Python program to check whether a file path is a file or a directory.

Sample Solution:-

Python Code:

import os  
path="abc.txt"  
if os.path.isdir(path):  
    print("\nIt is a directory")  
elif os.path.isfile(path):  
    print("\nIt is a normal file")  
else:  
    print("It is a special file (socket, FIFO, device file)" )
print()

Sample Output:

It is a normal file  

Flowchart:

Flowchart: Check whether a file path is a file or a directory.

Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to count the number of occurrence of a specific character in a string.
Next: Write a Python program to get the ASCII value of a character.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Unpack variables from iterable:

# One can unpack all iterables (tuples, list etc)
>>> a, b, c = 1, 2, 3
>>> a, b, c
(1, 2, 3)

>>> a, b, c = [1, 2, 3]
>>> a, b, c
(1, 2, 3)