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

Alan Gauld alan.gauld at btinternet.com
Tue Jul 1 01:26:27 CEST 2008

"David" <david at abbottdavid.com> wrote

> dir_input = raw_input('Enter dir: ')
> win_trace = ['*.ini', '*.db']
> files_removed = 0
> for root, dirs, files in os.walk(dir_input):
>    for trace in win_trace:
>        win_trace_path = os.path.join(root, trace)
>        for filename in glob.glob(win_trace_path):
>            if os.path.exists(filename):
>                print filename
>            else:
>                print 'No files found'

Note that at this point you have printed both names 
but you have not stored a reference to them.
Thus filename contains only the last name.

You need to create a list of the valid filenames.
You could use a list compreghension like so:

files = [f for f in glob.glob(win_trace_path) if os.path.exists(f)]
print files

> confirmation = raw_input('Confirm removal: ')
> if confirmation == 'y':
>    print "removing '%s'" % filename
>    os.remove(filename)
>    files_removed += 1

And now you are removing only one file, but you need to 
remove all of the files in your list so add a loop like:

> if confirmation == 'y':
     for filename in files:
        print "removing '%s'" % filename
        files_removed += 1

> elif confirmation == 'n':
>    pass
> else:
>    sys.exit()

The elif doesn't do anything so you can delete it.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list