Why don't isdir() and isfile() work for me?

J dreadpiratejeff at gmail.com
Wed Mar 10 02:47:25 UTC 2010


On Tue, Mar 9, 2010 at 21:19, Ray Parrish <crp at cmc.net> wrote:
> Hello,
>
> I am using Python Release 2.5.2, 21st February, 2008, and lookng at the
> corresponding document, it says -
>
> isfile(path)
>    Return True if path is an existing regular file. This follows
> symbolic links, so both islink() and isfile() can be true for the same
> path.
>
> isdir(path)
>    Return True if path is an existing directory. This follows symbolic
> links, so both islink() and isdir() can be true for the same path.
>
>
> And I am getting -
>
>  >>> import os
>  >>> isdir("/home/ray/links")
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> NameError: name 'isdir' is not defined
>  >>> os.isdir("/home/ray/links")
>  >>> os.isdir("/home/ray/links")
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> AttributeError: 'module' object has no attribute 'isdir'
>  >>> os.isfile("/home/ray/links")
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> AttributeError: 'module' object has no attribute 'isfile'
>  >>> import os.path
>  >>> os.isfile("/home/ray/links")
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> AttributeError: 'module' object has no attribute 'isfile'
>
> Could someone please explain to me why?

You're failing because you are not calling isdir() properly.  You have
to call it from os.path:

>>> print os.isdir("/home/bladernr")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'isdir'
>>> os.path.isdir("/home/bladernr")
True
>>> os.path.isdir("/home/bladernr/nosuchdir")
False

Or you have to import the function from os.path:

>>> from os.path import isdir
>>> isdir("/home/bladernr")
True
You could also do this
I saw the 2.5.2 documentation that shows isdir() as part of os, but I
think that's incorrect.  I think it's part of os.path and the
documentation is confusing.  For example, from the os.py source:

  from os.path import join, isdir, islink

Thats for the os.walk function. However, I also have 2.5.4 installed,
not 2.5.2 so there could be a difference there.

Any particular reason you're using 2.5.2 and not 2.5.6, or even 2.6?

Not trying to dissuade you from also asking for help, but this is more
an Ubuntu tech support list, and not so much a programming support
list... So you may also want to check this out:

http://www.python.org/community/lists/

Python has a huge community and you're far more likely to get answers
on python programming there than you would on a list that's not a
programming or python specific list.

Cheers,

Jeff




More information about the ubuntu-users mailing list