Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: run the second condition after the first one becomes false

I have a script where and if-else condition is given, the if takes the user input and process that if a certain directory is empty and fills that certain directory and the else runs if the directory is already full.

if not any(fname.endswith('.csv') for fname in os.listdir(certain_dir)): 
    def process_user_input:
     ....code....
        return something
else:
    def do_process_on_the_full_directory:
     ....code....
        return something_else

so, if the directory is empty, the first condition becomes True and the first process happens, and then I have to run the script again to have the else condition run on the directory that is now full. My question is whether there is a better way of doing that, so I do not have to run the script twice to get what I want, e.g, if there is a way to add order (first, fulfill the first condition, second after the directory is filled run the second condition).

like image 804
zara kolagar Avatar asked Feb 26 '26 14:02

zara kolagar


1 Answers

We can leverage decorators1 here to enforce the invariant.

def fill_if_empty(func):
    def wrapper(*args, **kwargs):
        if YOUR_CONDITION_TO_CHECK_FOR_EMPTY_DIR:
            """
            fill empty directory here.
            """
            process_user_input()

        func(*args, **kwargs)
    return wrapper

@fill_if_empty
def do_process_on_the_full_directory():
    """
    Run some process on directory
    """
    pass

do_process_on_full_directory() 

1. Checkout this post to know more about decorators: How to make function decorators and chain them together?

like image 159
Ch3steR Avatar answered Mar 01 '26 04:03

Ch3steR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!