Search code examples
pythonfilefilesystems

python how to delete all files whose name is a date in a folder


I have a folder with two categories of names for its sub-folders:

  • 1st category: sub-folders with names corresponding to a date
  • 2nd category: a sub-folder with the fixed name master.

Please refer to below screenshot.

enter image description here

How can I remove all the date folders and keep the master folder by python?

Until now I have used the below code which deletes all the folders, but now I want to keep the master folder.

try:
    shutil.rmtree('../../test/subtest/')
except OSError as e:
    print ("Error: %s - %s." % (e.filename, e.strerror))

Solution

  • This link contains the documentation of the module shutil. The first sentence of this documentation says:

    The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal. For operations on individual files, see also the os module.

    As suggest by the previous sentence a solution for the problem is by the use of os module.

    Use os module to list folders

    Try this code:

    import os
    import shutil
    
    parent_dir = '../../test/subtest/'
    my_list = os.listdir(parent_dir)
    for sub_dir in my_list:
        if sub_dir != 'master':
            print("deleting folder: " + sub_dir)
            try:
              shutil.rmtree(parent_dir + sub_dir)
            except OSError as e:
              print ("Error: %s - %s." % (e.filename, e.strerror))
    
    

    I add the import of the module os which permits to obtain the list of sub directory inside the parent dir; see the instruction:

    os.listdir(parent_dir)
    

    The deleting does not check if the sub-folder name contains a date but only if its name is different from 'master', but, if I have understood your question, I think that this is what you need.