stupid question about os.listdir

Erik Max Francis max at
Fri Jun 27 05:48:21 CEST 2003

Jason Kratz wrote:

> aha!   I found it!   its the call to os.path.isdir.   I'm not passing
> it
> a real pathname....just a string.  I need to set my entries in my dir
> list as real pathnames (ie: with the slashes)...not just the text.
> question is how ;)

A pathname _is_ just a string.  Presumably the problem is that you're
getting the results of os.listdir, which are just the names of the
contents of the directory, not the relative paths to them:

max at oxygen:~/tmp% mkdir subdir
max at oxygen:~/tmp% touch subdir/a subdir/b subdir/c
max at oxygen:~/tmp% ls subdir
a  b  c
max at oxygen:~/tmp% python
Python 2.2.3 (#1, May 31 2003, 21:31:33) 
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.listdir('subdir')
['a', 'b', 'c']

So just join the paths:

>>> for f in os.listdir('subdir'):
...  p = os.path.join('subdir', f)
...  print p, os.path.isfile(p)                  
subdir/a 1
subdir/b 1
subdir/c 1

   Erik Max Francis && max at &&
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ ike anybody, I would like to live a long life.
\__/  Dr. Martin Luther King, Jr.

More information about the Python-list mailing list