[Tutor] Cannot fix OSError

Alan Gauld alan.gauld at blueyonder.co.uk
Sat Jan 31 04:01:38 EST 2004


As per Danny's post I can't se anytthing obvious
although his tar explanation sounds good to me!
However...

> # code
> import tarfile, sys, os
>
> if len(sys.argv) <= 2:
>         print 'Error:', sys.argv[0], ' <tarfile.tar> <list of files>
>         sys.exit(1)
>
> tfile = sys.argv[1]
>
> totar = []
> for f in sys.argv[2:]:
>         if os.access(f, os.R_OK): # NOTE1
>                 totar.append(f)
>         else:
>                 print 'Could not access', f, 'to tar'
>
>
> tf = tarfile.TarFile(tfile, 'w')
> for f in totar:
>         tf.add(f)

> I could trap it in a try/except OSError block, but I'd
> like to know why the line NOTE1 does not simply cause
> the program to skip the unreadable file and continue ?

What's wrong with a try/except approach:

for f in sys.argv[2:]:
    try: tf.add(f)
    except OSERror: print 'Could not access', f, 'to tar'

Do you have any reason not to use the simpler approach?
- Like maybe you just wanted to try out the os access!... :-)

In general try/except leads to simpler code than explicit
tests. Only if the error is going to do significant and
unrecoverable damage do you need to test in advance.
This is why nearly all modern languages, from ADA
onwards use try/except style error processing.

Just a thought,

Alan G.




More information about the Tutor mailing list