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?
Asked
Active
Viewed 58 times
0

Martijn Pieters
- 1,048,767
- 296
- 4,058
- 3,343

info-farmer
- 255
- 3
- 18
-
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 Answers
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
- 5,026
- 24
- 37