Why the "except" part is running even when the file exists in the directory?

Viewed 14

The code below is trying to count the lines in the txt file.

fname = input('Enter the file name: ')
count = 0
if fname == 'na na boo boo':
    print('NA NA BOO BOO TO YOU - YOU HAVE BEEN PUNKED!')
elif fname != 'na na boo boo':
    try:
        fhand = open(fname)
        for line in fhand:
            count = count + 1
        print(f'There were {count} subject lines in the {fname}')
        quit()
    except:
        print(f'File cannot be opened: {fname}')
        quit()

But when I input the correct file name, it shows

There were 132045 subject lines in the mbox.txt.
File cannot be opened: mbox.txt

Isn't it supposed showing the following only?

There were 132045 subject lines in the mbox.txt.

Thanks in advance!

0 Answers
Related