Jacques Thibodeau
Jacques Thibodeau

Reputation: 959

Using pathlib in Google Colab: AttributeError: ‘PosixPath’ object has no attribute ‘ls’

If I run the following code:

from pathlib import Path
path = Path('data/mnist')
path.ls()

I get the following error:

AttributeError: ‘PosixPath’ object has no attribute ‘ls’

Looking at the Path class in pathlib, I find:

def __new__(cls, *args, **kwargs):
        if cls is Path:
            cls = WindowsPath if os.name == 'nt' else PosixPath
        self = cls._from_parts(args, init=False)
        if not self._flavour.is_supported:
            raise NotImplementedError("cannot instantiate %r on your system"
                                      % (cls.__name__,))
        self._init()
        return self

I'm guessing this means it will run PosixPath instead, which is:

class PosixPath(Path, PurePosixPath):
    """Path subclass for non-Windows systems.

    On a POSIX system, instantiating a Path should return this object.
    """
    __slots__ = ()

Not too sure what this means.

And actually, I can't find Path.ls() at all in the pathlib source code. Does this make sense? The coding tutorial I'm following used it (on a windows machine).

Upvotes: 5

Views: 8401

Answers (1)

panadestein
panadestein

Reputation: 1291

If one reads the documentation of the pathlib module one can confirm that, indeed, the class Path has no method ls. However, if your objective is to list files on a give directory, you could use the glob method like this:

from pathlib import Path

DIR = '.'
PATHGLOB = Path(DIR).glob('./*')
LS = [fil for fil in PATHGLOB]

I think this code snippet achieves the same that the code in your tutorial.

EDIT:

The fastai module does implement the ls method like this:

Path.ls = lambda x: [o.name for o in x.iterdir()]

I think the observed behavior is the result of the import * in the Jupyter notebook of the tutorial. This can be corroborated with the following code snippet:

from fastai import data_block

path = data_block.Path('.')
path.ls()

Upvotes: 4

Related Questions