我知道如何從云運行實體中的云存盤下載檔案。但是,我找不到在 python 中讀取檔案的語法。我希望立即將 csv 檔案轉換為 Pandas 資料幀,只需使用pd.read_csv('testing.csv'). 所以我的個人代碼看起來像,
download_blob(bucket_name, source_blob_name, 'testing.csv'). 那么我不應該能夠pd.read_csv('testing.csv')在云運行實體中做嗎?這樣做時,我在加載頁面時不斷獲取內部服務器。這似乎是一個簡單的問題,但我無法在任何地方找到它的示例。一切都只是下載檔案,我從未見過它被使用過。
def download_blob(bucket_name, source_blob_name, destination_file_name):
"""Downloads a blob from the bucket."""
# The ID of your GCS bucket
# bucket_name = "your-bucket-name"
# The ID of your GCS object
# source_blob_name = "storage-object-name"
# The path to which the file should be downloaded
# destination_file_name = "local/path/to/file"
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
# Construct a client side representation of a blob.
# Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve
# any content from Google Cloud Storage. As we don't need additional data,
# using `Bucket.blob` is preferred here.
blob = bucket.blob(source_blob_name)
blob.download_to_filename(destination_file_name)
print(
"Downloaded storage object {} from bucket {} to local file {}.".format(
source_blob_name, bucket_name, destination_file_name
)
)
uj5u.com熱心網友回復:
使用諸如“testing.csv”之類的檔案名意味著將檔案寫入當前目錄。當前目錄是什么?相反,請指定到已知目錄位置的絕對路徑。
下載到/tmp/目錄,例如'/tmp/testing.csv'。使用檔案系統空間會消耗記憶體,因為檔案系統是基于 RAM 的。確保 Cloud Run 實體有足夠的記憶體。
摘自 Cloud Run Container Runtime Contact:
容器的檔案系統是可寫的,并受以下行為的約束:
- 這是一個記憶體檔案系統,因此寫入它使用容器實體的記憶體。
- 當容器實體停止時,寫入檔案系統的資料不會持久化。
參考:檔案系統訪問
uj5u.com熱心網友回復:
download_as_bytes 如果您想將其直接加載到記憶體中,則是您正在尋找的功能。
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(source_blob_name)
data = blob.download_as_bytes()
pd.read_csv(StringIO(data))
https://googleapis.dev/python/storage/latest/blobs.html#google.cloud.storage.blob.Blob.download_as_bytes
Pandas 還支持直接從 Google Cloud Storage 讀取。https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html
任何有效的字串路徑都是可以接受的。該字串可以是一個 URL。有效的 URL 方案包括 http、ftp、s3、gs和 file。
所以像“gs://bucket/file”
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/368370.html
標籤:Python 文件 谷歌云平台 谷歌云存储 谷歌云运行
上一篇:讀取具有可變列數的CSV檔案
