如何使用Python访问Google云存储上的文件

时间:2018-07-18 02:32:08

标签: python google-cloud-storage google-compute-engine

我在存储桶中有一些文件,这些文件无法使用Cloud Shell从python访问。我创建了这个简单的示例:

open('gs://iwc/panda.jpg')

结果如下:

jklieb@cloudshell:~$ python demo.py                                                                                                                                                                          
Traceback (most recent call last):
  File "demo.py", line 1, in <module>
    open('gs://iwc/panda.jpg')
IOError: [Errno 2] No such file or directory: 'gs://iwc/panda.jpg'

但是使用gsutil时文件可见:

jklieb@cloudshell:~$ gsutil ls gs://iwc

gs://iwc/panda.jpg

我创建了一个单独的虚拟机实例(不是与Cloud Shell关联的临时实例),并且结果类似。

我还使用ctpu设置了一个TPU,同样无法访问另一个存储桶中的文件。 ctpu上的文档说,应正确设置权限,以允许访问存储分区。

我犯了一个简单的错误,对我来说太明显了吗?

1 个答案:

答案 0 :(得分:1)

解决方案是使用tensorflow.gfile.Open()访问文件:

jklieb@iwildcam2018:~$ python3
Python 3.5.3 (default, Jan 19 2017, 14:11:04)
[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow.gfile as gf
>>> gf.Open('gs://iwc/panda.jpg')
<tensorflow.python.platform.gfile.GFile object at 0x7f03e8b15f28>

这可以在云外壳和我创建的其他虚拟机上使用。 tensorflow.gfile.Glob()可用于获取与模式匹配的文件列表。