[Tutor] Comments appreciated

Alan Gauld alan.gauld at freenet.co.uk
Mon Dec 27 12:07:12 CET 2004


> example. The only thing I'm not clear about is how 'trashcan' can be
a
> local variable inside main() when it's required by both trash() and
> can()

It's not local. It is a global variable. It is defined outside
of any of the functions.

> The only thing that's missing is that this script can't handle paths
> like ~/dir/junkthis

Why not? What is so different between that path and the one in
the code below?

> Would a regular expression be the best way of finding the last /
> followed by some text to be able to chdir to junk files from another
> location?

No, there are functions for manipulating paths that should be able
to do that for you without resrting to regular expressions.
And those functions should be platform independant too!

>
> #!/usr/local/bin/python
>
> import os.path
> from os import mkdir, remove
> from sys import argv
> from shutil import rmtree
>
> trashcan = os.path.expanduser("~/.trashcan")

This is where trashcan is defined.

>
> def main(junk):
>     empty = False
>     if "-e" in junk:
>         empty = True
>         junk.remove("-e")
>
>     if not os.path.exists(trashcan):
>         os.mkdir(trashcan)

THis uses the definition above...

>
>     if len(junk) > 0:
>         trash(junk)
>
>     if empty:
>         can()
>
> def trash(junk):
>     for i in junk:
>         toss = trashcan + "/" + i

as does this...

>         if os.path.exists(toss):
>             if os.path.isdir(toss):
>                 rmtree(toss)
>             if os.path.isfile(toss):
>                 os.remove(toss)
>         os.rename(i, toss)
>
> def can():
>     for j in os.listdir(trashcan):

and this...

>         toss = trashcan + "/" + j
>         if os.path.isdir(toss):
>             rmtree(toss)
>         if os.path.isfile(toss):
>             os.remove(toss)
>
> if __name__ == '__main__':
>     main(argv[1:])
>
>



More information about the Tutor mailing list