Is this a dream or a nightmare? (Was Re: XML)
Tim Peters
tim_one at email.msn.com
Sun Oct 8 03:25:17 EDT 2000
[David T. Grove]
> die unless @d = map {"$basedir/$_"} grep {!-d && -w} readdir(dir);
[Grant Griffin]
> What in the heck does all _that_ mean?
[back to David]
> Actually, fully extended, it means "give me a platform independent
> list of writable (non-directory) files in that directory in a form
> that will allow me to name the files so that I can see them from
> elsewhere in my code regardless of where they are on disk, or halt
> immediately because if this doesn't work you might screw something
> up".
It generally takes no code in Python to "halt immediately ... if this
doesn't work" <0.5 wink>. I note some odd stuff about that Perl:
1. You skipped over the code to open the directory handle (dir).
Presumably you need a few more lines, like
$basedir = "/code";
die $! unless opendir(dir, $basedir);
2. The "!-d && -w" test doesn't make sense since the names returned
from readdir are just file names (not paths), and you didn't chdir()
to $basedir first. Unless that's another missing line:
die $! unless chdir $basedir;
3. Inserting a forward slash is not platform-independent (think e.g.
Macs, or even Windows if the paths are to be passed on to a DOS
command).
Python (2.0) code for doing all that correctly is no more lines (it could be
squashed into fewer but not profitably), but they are longer; OTOH, they do
more, and don't change the current directory:
import os, stat
basedir = os.path.normpath("/code")
paths = [os.path.join(basedir, f) for f in os.listdir(basedir)]
d = [p for p in paths if os.path.isfile(p)
if os.stat(p)[stat.ST_MODE] & 0222]
Curiously, there is no obvious x-platform way in Python to test whether a
file is writable. Doing a stat and mucking with the permission bits
directly is about as good as it gets. OTOH, people are sometimes surprised
by what "-w" means in Perl! That you're not mucking with the mode bits
directly there means Perl gets to surprise you by picking a meaning you may
not have intended -- at least in Python you can see exactly what "writable"
is testing. Although, if your background isn't Unix, it's utterly
mysterious <frown>. Python's os.access() instead is closest to the Perl
meaning, but doesn't exist on Mac Python. God only knows what works on Palm
Pilot Python <wink>.
x-platform-is-hard-ly y'rs - tim
More information about the Python-list
mailing list