Regarding searching directory and to delete it with specific pattern.

MRAB python at mrabarnett.plus.com
Wed Dec 1 12:35:53 EST 2010


On 01/12/2010 07:07, Ramprakash Jelari thinakaran wrote:
> Hi all,
> Would like to search list of directories with specific pattern and
> delete it?.. How can i do it?.
> Example: in /home/jpr/ i have the following list of directories.
> 1.2.3-2,  1.2.3-10, 1.2.3-8, i would like to delete the directories
> other than 1.2.3-10 which is the higher value?..
>
Use os.listdir to get a list of the names in the directory.

Use os.path.isdir to identify those which are subdirectories.

Identify the names which match the pattern, eg:

     name.startswith("1.2.3-") and name[6 : ].isdigit()

Identify the 'highest' name (it's the one with the maximum value of
int(name[6 : ])).

Remove each of the unwanted subdirectories with shutil.rmtree.

It's also a good idea if initially it doesn't actually remove the
unwanted directories, but just prints out the paths of them, because
you really don't want to discover that you've made a mistake and it has
deleted something important! :-)



More information about the Python-list mailing list