[英]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:查看 pathlib 中的路径 class ,我发现:
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:我猜这意味着它将运行 PosixPath,即:
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.实际上,我在 pathlib 源代码中根本找不到 Path.ls() 。 Does this make sense?这有意义吗? The coding tutorial I'm following used it (on a windows machine).我正在遵循的编码教程使用它(在 windows 机器上)。
If one reads the documentation of the pathlib module one can confirm that, indeed, the class Path
has no method ls
.如果阅读pathlib模块的文档,可以确认 class Path
确实没有方法ls
。 However, if your objective is to list files on a give directory, you could use the glob
method like this:但是,如果您的目标是列出给定目录中的文件,则可以使用glob
方法,如下所示:
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.我认为此代码片段与您教程中的代码相同。
The fastai module does implement the ls
method like this: fastai 模块确实实现了ls
方法,如下所示:
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.我认为观察到的行为是本教程 Jupyter 笔记本中 import *
的结果。 This can be corroborated with the following code snippet:这可以通过以下代码片段得到证实:
from fastai import data_block
path = data_block.Path('.')
path.ls()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.