Search code examples
pythonerror-handlingtry-except

How can I iterate through a file and raise a custom Exception if there is not enough input?


I have been following the 'Python for dummies' book and there is one example that doesn't print out the result as I expected.

class Error(Exception):
    pass
class NotEnoughStuffError(Error):
    pass
try:
    thefile = open('people.csv')
    line_count = len(thefile.readlines())
    if line_count < 2:
        raise NotEnoughStuffError
except NotEnoughStuffError:
    print('Not Enough Stuff')
except FileNotFoundError:
    print('File not found')
    thefile.close()
else:
    for line in thefile:
        print(line)
    thefile.close()
    print('Success!')

Question 1: When it prints, it should show all the lines from thefile. However, it only prints 'Success!' Why the content from thefile was not printed?

Question 2: I replaced the code:

class Error(Exception):
    pass
class NotEnoughStuffError(Error):
    pass

with

class NotEnoughStuffError(Exception):
    pass

Do they return the same result? Is 'Exception' a built-in class in Python?


Solution

  • Problem is because you used readlines() and it moved pointer to the end of file and when you later use for line in thefile: then it tries to read from end of file. And it reads nothing from the end of file and it display nothing.

    You would have assing list with lines to variable

     all_lines = thefile.readlines()
     line_count = len(all_lines)
    

    and later use this list

     for line in all_lines:
        print(line)
    

    Or you would have to move pointer to the beginning of file before you try to read again data

     thefile.seek(0)
    
     for line in thefile:
        print(line)