w3resource

Python: Find path refers to a file or directory when you encounter a path name

Python Basic: Exercise-108 with Solution

Write a Python program to find the path to a file or directory when you encounter a path name.

Sample Solution:

Python Code:

# Import the 'os.path' module for working with file paths.
import os.path
# Iterate through a list of file paths, including '__file__', the directory of '__file__', '/', and a broken link.
for file in [__file__, os.path.dirname(__file__), '/', './broken_link']:
    # Print the name of the current file.
    print('File        :', file)

    # Check if the file path is an absolute path using 'os.path.isabs()'.
    print('Absolute    :', os.path.isabs(file))

    # Check if the file path points to an existing file using 'os.path.isfile()'.
    print('Is File?    :', os.path.isfile(file))

    # Check if the file path points to an existing directory using 'os.path.isdir()'.
    print('Is Dir?     :', os.path.isdir(file))

    # Check if the file path is a symbolic link using 'os.path.islink()'.
    print('Is Link?    :', os.path.islink(file))

    # Check if the file path exists (regardless of its type) using 'os.path.exists()'.
    print('Exists?     :', os.path.exists(file))

    # Check if the symbolic link exists using 'os.path.lexists()'.
    print('Link Exists?:', os.path.lexists(file))

Sample Output:

File        : 26cb6a20-266f-11e7-a9c1-cf681af3cdf1.py              
Absolute    : False                                                
Is File?    : True                                                 
Is Dir?     : False                                                
Is Link?    : False                                                
Exists?     : True                                                 
Link Exists?: True  
------
Is Dir?     : False                                                
Is Link?    : False                                                
Exists?     : False                                                
Link Exists?: False 

Flowchart:

Flowchart: Find path refers to a file or directory when you encounter a path name.

Python Code Editor:

 

Previous: Write a Python program to retrieve file properties.
Next: Write a Python program to check if a number is positive, negative or zero.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-108.php