0

I am having 100 sub-folders in a folder. Some of the sub-folder is having following count result(ls 24*.pdf | wc) as one (1). How can i delete the sub-folders (1) by python. I think that I can use if function. If the count is 1, delete the folder. How?

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
info-farmer
  • 235
  • 3
  • 14
  • This seems to be a duplicate of https://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder – Jerinaw Jul 29 '17 at 02:59

1 Answers1

1

You can use the os module to remove the directory and glob to get the files that match your query like:

import glob
files = glob.glob("mydir/24*.pdf")

Then get the count with:

file_count = len(files)

Then check if it's > 1, remove it with os.rmdir().

import os
if file_count > 1:
    os.rmdir("mydir")

You can get the file list using os.listdir('mydir'), but you'd have to filter the filenames manually.

Cory Madden
  • 4,648
  • 21
  • 36