Trying to delete directories with an 'X' as the 4th character in the name

I have a folder with folders inside that contain files so I know I need to use shutil.rmtree but choosing to delete the folders where the 4th character is an 'X' is throwing me off so do I need a counter? So far I have:

import shutil

for some_dir in 'dir_name':
    if some_dir[4] == 'X':

for x in 'dir_name':

1 answer

  • answered 2022-01-23 03:01 rpontual

    As shutil.rmtree(...) will remove entire directories, the sample code has its line commented out. I suggest testing the code until you are satisfied and uncommenting the line (removing "#") to enable shutil.rmtree(). The function assumes the directory names are provided as a list of names:

    import shutil
    dir_name = ['ThisX a test', 'This is a dir to keep', 'yessX']
    for some_dir in dir_name:
        if len(some_dir) > 4:
            if some_dir[4] == 'X':
                print('Delete ', some_dir)
                # shutil.rmtree(some_dir)  # <- uncomment this line when you are ready
        print('Keep ', some_dir)

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum