【问题标题】:s3fs and Python os.walks3fs 和 Python os.walk
【发布时间】:2021-10-30 08:27:09
【问题描述】:

我正在尝试找出一种从 S3 存储桶中读取图像的方法。现在,我的设置是使用 s3fs 挂载存储桶,然后使用带有 os.walk 的 python 脚本遍历每个单独的图像并使用 numpy 对它们进行一些操作。

然而,

的输出
os.walk("mnt/") 

什么都不是!该命令在已安装的驱动器中看不到任何文件,但如果我手动找到图像

plt.imread("mnt/path/to/file")

我收到了图片。我束手无策,试图弄清楚这一点。有什么想法吗?

【问题讨论】:

  • 这在我的测试中有效。请注意,os.walk 返回一个生成器,您必须通过 for 循环或内置列表使用该生成器。

标签: python numpy amazon-s3 s3fs


【解决方案1】:

从 S3 挂载的存储桶在您的文件系统中的行为与普通文件/目录不同,因此像 os.walk 这样的语句不会像您预期的那样工作。最好的办法是使用库从 Python 本身中搜索 S3 存储桶并与之交互。

我建议研究一下 boto,它有很多与 AWS 交互的工具。另请查看 AWS Python 开发工具包。

博托:https://github.com/boto/boto 适用于 Python 的 AWS 开发工具包:https://aws.amazon.com/sdk-for-python/

【讨论】:

    【解决方案2】:

    这里有一些错误。我认为{dirpath}{filepath} 应该是第 5 行的{dirpath}/{filename}filename 应该是第 2 行的filenames,但在其他方面很有帮助!

    【讨论】:

      【解决方案3】:

      作为替代方案,我仅使用 boto3 实现了类似于 os.walk() 的东西。

      请参阅相关问题中的my answer

      【讨论】:

        【解决方案4】:

        你可以这样做:

        s3 = s3fs.S3FileSystem()
        for dirpath, dirnames, filename in s3.walk(<your bucket name>):
        # care about the how many directories your bucket have
            for filename in filenames:
                file_path = f'{dirpath}{filepath}'
                    with s3.open(file_path, 'rb') as f:
                        # do your numpy stuff with the "f" object
        

        上面的代码会遍历整个bucket,并且只有当bucket根目录下有文件时才有效,如果之前有目录,添加if语句,例如:

        if dirpath.split('/') == <depth of the directory with the files>:
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-08-19
          相关资源
          最近更新 更多