1

I have a long list of directories, with something like this

C:\Users\vanstrie\Desktop\ntnu\SCHEMA\2012\07_paper\results\026\onsets

I want to parse through folders 001-040 (026 shown above) and remove the onsets subdirectory with all files and subfolders that are in it. I am unsure how to achieve this with python 3. If you have a solution, please advise. Many thanks in advance.

Niels

2 Answers 2

2

I would think that something like this should work...

import glob
import os.path
import shutil
files_dirs = glob.glob(r'C:\Users\vanstrie\Desktop\ntnu\SCHEMA\2012\07_paper\results\*')
for d in files_dirs:
    head,tail = os.path.split(d)
    try:
        if (0 < int(tail) < 41) and (len(tail) == 3):  #don't want to delete `\results\3\onsets` I guess...
           print("about to delete:",d)
           shutil.rmtree(os.path.join(d,'onsets'),ignore_errors=True)
    except ValueError:  #apparently we got a non-integer.  Leave that directory.
        pass

As with anything when deleting files, I would definitely print the things that would be deleted on a first pass -- Just to make sure the script is actually working as expected (and to make sure you don't delete something you want to keep).

Sign up to request clarification or add additional context in comments.

1 Comment

will try it out in a moment and update the result. A million thanks!
1
import shutil, os.path

root_folder = "C:\\Users\\vanstrie\\Desktop\\ntnu\\SCHEMA\\2012\\07_paper\\results"
suffix = "onsets"

for i in range(1,41):
  folder = os.path.join( root_folder, "%03d" % i, suffix )
  shutil.rmtree( folder, ignore_errors=True, onerror=None )

1 Comment

This is kind of nice. I don't use rmtree frequently, but I'm guessing this will pass silently if the directory doesn't exist (due to ignore_errors = True). If so, that makes this a much more concise answer than mine...(+1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.