0

I am writing a program (which reads file from command line arguments) and some exceptions to handle. I have 2 exceptions:1)If the file i want to read doesn't exist in the path i should give an exception.2)If the format of the file i want to read doesn't match i should give another exception.

try:
    f = open(sys.argv[2], 'r')
    commands = [[line.split()] for line in f.readlines()]
    f.close()
except FileNotFoundError:
    print('Input file not found')
    sys.exit()
    

For first exception i did this but i couldn't do the second one what should i do?

Note: Second exception means if i wrote x.txt in command line and if x.pptx exists i should give an exception like "Format is not correct".

Alexandra
  • 27
  • 5
  • Are you sure you want `[line.split()]`? `split` already returns a list; you probably just want `[line.split() for line in f]`. (Calling `readlines` is *definitely* not necessary.) – chepner Dec 24 '20 at 19:22

2 Answers2

0

You can define a custom exception:

class MyException(Exception):
    pass

and raise it if the conditional for the file format check fails:

try:
    f = open(sys.argv[2], 'r')
    commands = [[line.split()] for line in f.readlines()]
    if incorrect_format(sys.argv[2]):
        f.close()
        raise MyException
    f.close()
except FileNotFoundError:
    print('Input file not found')
    sys.exit()
except MyException:
    print('File format not correct')
    sys.exit()

You can define the logic for file format check in the function incorrect_format. Example:

def incorrect_format(filename):
    return filename.split(".")[-1] == "txt"
Jarvis
  • 8,494
  • 3
  • 27
  • 58
0
import os.path
from os import path
path.exists("somefile.txt")

So, this checks if somefile.txt is in the same directory. (it will return True or False). If no, instead of raising a error, you can directly print "Format not correct"

import os.path
from os import path


try:
    f = open(sys.argv[2], 'r')
    commands = [[line.split()] for line in f.readlines()]
    f.close()
   
    exitsOrNot = path.exists("somefile.txt")
    if exitsOrNot == False:
        print("Format not correct") 
except FileNotFoundError:
    print('Input file not found')
    sys.exit()
    
Srishruthik Alle
  • 500
  • 3
  • 14