'How to raise exceptions for when file is not specified and when the specified file does not exists?pyth
I a script I have:
if __name__ == '__main__':
try:
file = sys.argv[1]
with open (file, 'rb') as img_file:
I run the script in terminal as:
python3 script.py file
I want to account for 2 cases where the specified file does not exist and the script prints "file does not exists" and also when the file is not being specified by the user (python3 script.py) and the script prints "file not specified". How should these 2 exceptions be included in the script?
Solution 1:[1]
import sys
try:
file = sys.argv[1]
with open(file, 'rb') as img_file:
pass
except IndexError:
print("file not specified")
raise
except FileNotFoundError:
print("file doesn't exist")
raise
Solution 2:[2]
I recommend validate before logic directly, not catch the exception with the hole block.
import os
import sys
if __name__ == '__main__':
if len(sys.argv) < 2:
print('file not specified')
sys.exit(1)
file = sys.argv[1]
if not os.path.exists(file):
print('file {} does not exists'.format(file))
sys.exit(1)
if not os.path.isfile(file):
print('{} is not a file'.format(file))
sys.exit(1)
with open (file, 'rb') as img_file:
# TODO: your logic here
pass
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rzlvmp |
| Solution 2 | Xianzhi Xia |
