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 the 'os' module to access operating system functionalities.
import os
# Define the path to a file or directory named 'abc.txt'.
path = "abc.txt"
# Check if the path refers to a directory.
if os.path.isdir(path):
# Print a message indicating that it is a directory.
print("\nIt is a directory")
# Check if the path refers to a regular file.
elif os.path.isfile(path):
# Print a message indicating that it is a normal file.
print("\nIt is a normal file")
# If the path doesn't match a directory or a regular file, assume it's a special file (e.g., socket, FIFO, device file).
else:
# Print a message indicating that it is a special file.
print("It is a special file (socket, FIFO, device file)")
# Print a newline character for spacing.
print()
Sample Output:
It is a normal file
Flowchart:
Python Code Editor:
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 Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/python-basic-exercise-85.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics