KevOMalley743
KevOMalley743

Reputation: 581

raising an exception if a folder doesn't exist pathlib python

I'm working on automating some record keeping and am trying to create a class that represents the folders where the records are stored.

I want to raise an exception, or make the class creation fail if the folder doesn't exit


from pathlib import Path

class Records:
    
    def __init__(self, location):
        self.location = location
         if Path(f'{self.location}').exists:
            pass
         else:
            print('No folder exists at the location specified')

a = Records('path\\to\\a\\dir')
b = Records('not\\a\\real\\dir')

print(a.location)
print(b.location)

I have tested the above with various permutations and I've tried try:except blocks b is still created as a Records object even though the folder doesn't exist.

Any guidance would be much appreciated.

Upvotes: 1

Views: 4130

Answers (2)

Gabriel
Gabriel

Reputation: 979

You should probably use is_dir instead of exists if you want to check specifically for a folder. Either way, you should add brackets to call it. Then, as Emmanuel said, if you want the class creation to fail, you can raise an error. Here a FileNotFound error could be a good candidate :

class Records:

    def __init__(self, location):
        self.location = location
        if Path(f'{self.location}').is_dir(): # don't forget ()
            pass
        else:
            raise FileNotFoundError('No folder exists at the location specified')

Afterwards you have several ways to handle it in your code. If you want the code to crash on class creation failure, just call it.

b = Records('not\\a\\real\\dir') # causes program to crash with a FileNotFoundError

If you want your program to continue, do

try:
     b = Records('not\\a\\real\\dir')
except FileNotFoundError:
     print("The class could not be created as the specified folder does not exist")

# do other stuff here, calling b will fail though

Upvotes: 1

Emmanuel
Emmanuel

Reputation: 105

I want to raise an exception

To raise an exception you must explicitely call raise.

or make the class creation fail if the folder doesn't exit

Please be more specific, as fail is not precise enough. Raising an exception will cause your program to stop if not caught.

Upvotes: 1

Related Questions