簡體   English   中英

我正在嘗試使用python代碼讀取Google Cloud Storage存儲桶中的文件,但出現錯誤

[英]I am trying to read a file in in Google Cloud Storage bucket with a python code but getting the error

我正在嘗試讀取存儲在Google Cloud Storage存儲桶python中的文件:

textfile = open("${gcs_bucket}mdm/OFF-B/test.txt", 'r') 
times = textfile.read().splitlines() 
textfile.close() 
print(getcwd()) 
print(times)

該文件位於該位置,但是我收到以下錯誤:

File "/var/cache/tomcat/temp/interpreter-9196592956267519250.tmp", line 3, in <module>
  textfile = open("gs://tp-bi-datalake-mft-landing-dev/mdm/OFF-B/test.txt", 'r')
IOError: [Errno 2] No such file or directory: 'gs://tp-bi-datalake-mft-landing-dev/mdm/OFF-B/test.txt'

那是因為您試圖將其讀取為本地文件。

要從Cloud Storage中讀取內容,您需要導入庫並使用客戶端。

檢查類似的Stackoverflow Question

在您的情況下,它將類似於:

from google.cloud import storage

# Instantiates a client
client = storage.Client()

bucket_name = 'tp-bi-datalake-mft-landing-dev'

bucket = client.get_bucket(bucket_name)

blob = bucket.get_blob('mdm/OFF-B/test.txt')

downloaded_blob = blob.download_as_string()

print(downloaded_blob)

另外,您將需要安裝該庫 ,只需運行以下命令即可:

在運行代碼之前,請pip install google-cloud-storage

您還可以在這里找到更多Google Cloud Storage Python示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM