gpt4 book ai didi

python - google colaboratory 和 google cloud 之间的接口(interface)

转载 作者:太空狗 更新时间:2023-10-30 02:53:35 27 4
gpt4 key购买 nike

在 google colaboratory 中,如果我想读/写到在 google cloud 中创建的给定存储桶中的文件夹,我该如何实现?

我创建了一个存储桶,存储桶中的一个文件夹,并将一堆图像上传到其中。现在来自 colaboratory,使用 jupyter notebook,想要创建多个子目录以将这些图像组织到 train、validation 和 test 文件夹中。

随后访问相应的文件夹以训练、验证和测试模型。

使用 Google Drive,我们只需在身份验证后使用以下命令更新路径以定向到特定目录。

import sys
sys.path.append('drive/xyz')

我们在桌面版上也做了一些类似的事情

import os
os.chdir(local_path)

Google Cloud Storage 是否存在类似的东西?

I colaboratory FAQs,里面有读写单个文件的程序,这里需要设置整个路径。将主目录重新组织成子目录并分别访问它们将是乏味的。

最佳答案

一般来说,尝试在本地机器上安装 GCS 桶并不是一个好主意(这将允许您像您提到的那样使用它)。来自 Connecting to Cloud Storage buckets :

Note: Cloud Storage is an object storage system that does not have the same write constraints as a POSIX file system. If you write data to a file in Cloud Storage simultaneously from multiple sources, you might unintentionally overwrite critical data.

假设您不顾警告继续操作,如果您使用 Linux 操作系统,您可以使用 Cloud Storage FUSE 安装它。适配器。见相关How to mount Google Bucket as local disk on Linux instance with full access rights .

从 python 应用程序访问 GCS 的推荐方法是使用 Cloud Storage Client Libraries , 但访问文件会有所不同比在你的片段中。您可以在 Python Client for Google Cloud Storage 找到一些例子。 :

from google.cloud import storage
client = storage.Client()
# https://console.cloud.google.com/storage/browser/[bucket-id]/
bucket = client.get_bucket('bucket-id-here')
# Then do other things...
blob = bucket.get_blob('remote/path/to/file.txt')
print(blob.download_as_string())
blob.upload_from_string('New contents!')
blob2 = bucket.blob('remote/path/storage.txt')
blob2.upload_from_filename(filename='/local/path.txt')

更新:

Colaboratory 文档推荐了另一种我忘记的方法,基于 Google API Client Library for Python ,但请注意,它也不像常规文件系统那样运行,它使用本地文件系统上的中间文件:

关于python - google colaboratory 和 google cloud 之间的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49021464/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com