[Tutor] Deleting specified files using a python program...help withcode?

Alan Gauld alan.gauld at btinternet.com
Sun Jun 29 17:51:16 CEST 2008


"Saad Javed" <sbjaved at gmail.com> wrote 

> *import os

Not sure what the asterisk at the front is for?
The import should be aligned with the left margin.
 
> list = ['*.ini', '*.db']

Its a bad idea to call things list since you hide 
the builtin list function for converting things to 
lists...

> for root, dirs, files in os.walk('/home/saad'):
> **for list in files:

Assuming the asterisks indicate spaces the use of 
list here hides your list above.

I suspect what you meant was something like

for file in files:
    if file in list:
       os.remove(file)

Except that won't work with wildcards.

So you might need to do:

for file in files:
    for ending in list:
        if file.endswith(ending):
             os.remove(file)

Actually I suspect you would be better using glob.glob 
here rather than os.walk. Alternatively, using os.basename 
to split off the extension and comparing that might be better.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list