Getting all the *files* from a directory -- A better way??

Ben Hutchings ben.hutchings at roundpoint.com
Wed Mar 28 17:26:17 EST 2001


"Ken Seehof" <kens at sightreader.com> writes:

> "Paul Jackson" <pj at sgi.com> wrote:
<snip>
> > Close - better to use os.path.join (more portable across
> > operating environments with different path component
> > separator characters, such as '\' in DOS/Windows).
> 
> Actually '/' is generally portable.

Not to MacOS.

> I use os.path.join for combining
> variables, but I use '/' within hard-coded relative paths.
> 
> e.g.:
> f = os.path.join(root, 'doc/chapter2/spam.html')
> rather than
> f = os.path.join(root, os.path.join('doc', os.path.join('chapter2',
> 'spam.html'))))
> 
> This is fine because open() and all other file functions automagically
> normalize the path to the operating system.

No they don't.  Windows system calls that take file names accept '/'
as a name separator, so this works on both Windows and Unix (and
AmigaOS).  (For share names and registry key names, however, Windows
is not so liberal.)

> Warning: if you want to use the result in a command line
> (e.g. os.popen()) be sure to normalize the path with
> os.path.normpath().

Generally good practice, but in fact many command-line programs for
Windows accept '/' in file names.

-- 
Any opinions expressed are my own and not necessarily those of Roundpoint.



More information about the Python-list mailing list