stupid question about os.listdir

Peter Hansen peter at engcorp.com
Fri Jun 27 05:43:25 CEST 2003


Jason Kratz wrote:
> 
> def getdirs(path):
>      os.chdir(path)
>      for entry in os.listdir(path):
>          if os.path.isdir(entry):
>              dirs.append(entry)
> 
> if I run this from the command line on linux with 'python backup.py' it
> works *if* I have os.chdir in there.  if I comment it out it doesnt list
> starting from the root dir...it starts in my home dir.

This might mean you are not passing it an absolute path, but 
instead a relative one.  Absolute paths (on Linux) are those
which start with a / (forward slash).  Anything without that
will start from the current directory only.

But without actual examples of which paths are failing, as
Ben has asked for, we know nothing for certain.

Is it also possible that you are not having a problem with listdir()
at all, but with the values you are passing to os.path.isdir()?
You realize that os.listdir() returns names that are *relative*
to the path parameter you give it?  So that if you then pass those
to isdir() you will get nothing useful if you don't first do
this instead? :

  entry = os.path.join(path, entry)
  if os.path.isdir(entry):
     dirs.append(entry)

-Peter




More information about the Python-list mailing list