13.4. File Path Errors¶
13.4.1. SetUp¶
>>> from pathlib import Path
>>> Path('/tmp/myfile.txt').unlink()
13.4.2. FileNotFoundError¶
Problem:
>>> open('/tmp/myfile.txt')
Traceback (most recent call last):
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/myfile.txt'
Solution:
>>> try:
... file = open('/tmp/myfile.txt')
... except FileNotFoundError:
... print('Sorry, file not found')
Sorry, file not found
13.4.3. PermissionError¶
Problem:
>>> open('/etc/sudoers')
Traceback (most recent call last):
PermissionError: [Errno 13] Permission denied: '/etc/sudoers'
Solution:
>>>
... try:
... file = open('/etc/sudoers')
... except PermissionError:
... print('Sorry, permission denied')
Sorry, permission denied
13.4.4. IsADirectoryError¶
Problem:
>>> open('/tmp')
Traceback (most recent call last):
IsADirectoryError: [Errno 21] Is a directory: '/tmp'
Solution:
>>> try:
... file = open('/tmp')
... except IsADirectoryError:
... print('Sorry, path leads to directory')
Sorry, path leads to directory
13.4.5. Use Case - 0x01¶
>>> try:
... file = open('/tmp/myfile.txt')
... except FileNotFoundError:
... print('Sorry, file not found')
... except PermissionError:
... print('Sorry, permission denied')
... except IsADirectoryError:
... print('Sorry, path leads to directory')
Sorry, file not found