1
\$\begingroup\$

I have a project where, every time I run it, I have to:

  • test if some folders exist, and create them if they don't exists.
  • remove their content if the folders already exist.

This is the code that I developed to do this:

import os
import pathlib

def clean_Folders(directory):
    folders = ['preprocessed', 'results', 'tmp']
    for folder in folders:
        if not os.path.exists(os.path.join(directory, folder)):
            os.makedirs(os.path.join(directory, folder))
    for filepath in pathlib.Path(directory).glob('**/*'):
        try:
            os.remove(filepath.absolute())

        except:
            print('something went wrong')

I had another idea which is creating the folders every time I run my project (without doing the existence test nor caring about what the already contain).
Here is the code:

import os
import shutil

def clean_Folders(directory):
    folders = ['preprocessed', 'results', 'tmp']
    for folder in folders:
        try:
            if os.path.exists(os.path.join(directory, folder)):
                    shutil.rmtree(os.path.join(directory, folder))
            os.makedirs(os.path.join(directory, folder))
        except:
            print('something went wrong')  

Which one of the solutions is more optimized and more professional?
Thank you.

\$\endgroup\$
2
\$\begingroup\$

The second one is definitively safer, since in the first one you actually remove everything in all subfolders of directory, not just in the three folders you want to remove.

Some additional comments:

  • I would save the result of os.path.join(directory, folder) in a variable, you calculate it like three times.
  • Have a look at Python's official style-guide, PEP8. It recommends using lower_case both for variables and for function names, so your function should be called clean_folders.
  • A bare except is basically never a good idea. And even worse is a bare except with the unhelpful message 'something went wrong'. You want to either catch the exception you are looking for and handle it, or let the exception bubble to the top and halt the execution of the program. So, find out what kind of exception you actually want to catch (maybe IOError?). Or at least use except Exception, which excludes exceptions like e.g. the user pressing Ctrl+C being caught.
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thank you for the answer and thank you another time for the very useful comments! \$\endgroup\$ – singrium Feb 14 '19 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.