【问题标题】:Gsutil - How can I check if a file exists in a GCS bucket (a sub-directory) using GsutilGsutil - 如何使用 Gsutil 检查 GCS 存储桶(子目录)中是否存在文件
【发布时间】:2015-06-04 03:07:30
【问题描述】:

我有一个 GCS 存储桶,其中包含路径中的一些文件

gs://main-bucket/sub-directory-bucket/object1.gz

我想以编程方式检查子目录存储桶是否包含一个特定文件。我想使用 gsutil 来做到这一点。

这是怎么做到的?

【问题讨论】:

    标签: python google-cloud-storage gsutil


    【解决方案1】:

    您可以使用gsutil stat 命令。

    【讨论】:

    • 谢谢 jterrace。我确实检查了 gsutil stat - 特别是 gsutil -q stat 选项。它看起来非常适合我的用例。然而,谷歌表示我们只能在主目录中的对象上使用 gsutil -q stat。也就是说,它不适用于子目录中包含的对象。有没有其他方法可以检查子目录中的对象是否存在?谢谢!
    • 子目录实际上并不存在。请看cloud.google.com/storage/docs/gsutil/addlhelp/…
    • @activelearner - 它专门谈论目录本身,而不是里面的对象,例如gsutil stat gs://bucket/dir/subdir/foo.txt 可以正常工作。我将提交一个关于更新文档的错误以使其更清晰。
    【解决方案2】:

    使用gsutil stat 命令。要访问具有更多文件的子目录,请使用通配符(*)。

    例如:

    gsutil -q stat gs://some-bucket/some-subdir/*; echo $?
    

    在你的情况下:

    gsutil -q stat gs://main-bucket/sub-directory-bucket/*; echo $?
    

    结果0表示存在1 表示不存在

    【讨论】:

      【解决方案3】:

      还有gsutil ls(https://cloud.google.com/storage/docs/gsutil/commands/ls)

      例如

      gsutil ls gs://my-bucket/foo.txt
      

      输出是相同的文件路径或“CommandException: One or more URLs matched no objects.

      【讨论】:

        【解决方案4】:

        如果出于某种原因您想根据该列表的结果执行某些操作(例如,如果目录中有 parquet 文件,则加载 bq 表):

        gsutil -q stat gs://dir/*.parquet; if [ $? == 0 ]; then bq load ... ; fi

        【讨论】:

          【解决方案5】:

          如果您的脚本允许非零退出代码,则:

          #!/bin/bash
          
          file_path=gs://main-bucket/sub-directory-bucket/object1.gz
          gsutil -q stat $file_path
          status=$?
          
          if [[ $status == 0 ]]; then
            echo "File exists"
          else
            echo "File does not exist"
          fi
          
          

          但是,如果您的脚本设置为因错误而失败,那么您就不能使用退出代码。这是一个替代解决方案:

          #!/bin/bash
          trap 'exit' ERR
          
          file_path=gs://main-bucket/sub-directory-bucket/object1.gz
          result=$(gsutil -q stat $file_path || echo 1)
          if [[ $result != 1 ]]; then
            echo "File exists"
          else
            echo "File does not exist"
          fi
          
          

          【讨论】:

          • 这应该是正确的答案,因为它也解释了退出代码的情况。
          【解决方案6】:

          只需使用 ls 命令并计算输出的行数。

          如果为0则文件不存在,如果为1则文件存在。

          file_exists=$(gsutil ls gs://my_bucket/object1.gz | wc -l)
          

          当然也可以用于很多文件。

          files_number=$(gsutil ls gs://my_bucket/object* | wc -l)
          

          【讨论】:

          猜你喜欢
          • 2020-06-30
          • 2018-11-04
          • 2021-06-01
          • 2013-09-29
          • 2021-02-05
          • 2020-11-12
          • 2020-07-22
          • 2019-06-17
          • 1970-01-01
          相关资源
          最近更新 更多