Resuming in exception handling

Nathaniel Gray n8gray at caltech.edu.is.my.e-mail.address
Tue Apr 17 03:58:45 EDT 2001


Lucas Vogel wrote:
> I get an OSError about a file permission on one of the files it tries
> to delete. When it gets that exception I want it to simply move on to
> the next file. How do I do that?

The right way to do this is to wrap just the os.remove() in the try block.  
Here's the new version:

<code snippet>
import os, glob
 
#place all LW*.txt files in list and kill them
 
LWPath = 'C:\\LAND WARRIOR 1.0'

flist = glob.glob( LWPath + '\\LW*.txt')
for fname in flist:
    print 'removing ' + fname
 
    try:
        os.remove(fname)
    except OSError:
        print('skipping ' + fname)
        # Next line best avoided
        # flist.remove(fname) 
        # Modifying a container while iterating over it can get messy
        # (see below)
del flist

</code snippet>

Here's a simple example of why not to delete from a container that you're 
iterating over unless you're sure you know what you're doing:

<code>
jim = ['one', 'two', 'three', 'four', 'five']
for i in jim:
  try:
    print i
    if i == 'three': raise 'badmojo!'
  except:
    print 'skipping', i
    jim.remove(i)
</code>

The program's output is:
one
two
three
skipping three
five

Cheers,
-n8

-- 
_.~'^`~._.~'^`~._.~'^`~._.~'^`~._.~'^`~._
             Nathaniel Gray
   California Institute of Technology
     Computation and Neural Systems
     n8gray <at> caltech <dot> edu
_.~'^`~._.~'^`~._.~'^`~._.~'^`~._.~'^`~._




More information about the Python-list mailing list