【问题标题】:How can I read the contents of a file in a GCP bucket?如何读取 GCP 存储桶中文件的内容?
【发布时间】:2021-03-27 15:55:20
【问题描述】:

我需要读取当前位于 GCP 存储桶中的文件的前 20 行。我正在尝试通过带有 HTTP 触发器的 Google 函数读取文件的内容。我可以访问该文件,但是当我尝试使用“return data_string”返回内容以便我可以看到输出时,它不起作用。我不必返回该文件的全部内容,这就是为什么我只需要前 20 行。理想情况下,我想要一些命令来读取内容并获取文件的每一行并将其添加到一个数组中,然后我可以从中获取特定的行。如果我在我的开发 PC 上使用 Google 存储桶中的相同文件执行此操作并使用 open() 命令,它就可以正常工作。我可以阅读每一行并获取我想要的内容,但我需要通过 Google 函数对其进行测试。请帮忙!

这是我目前的代码。

 storage_client = storage.Client()
    #define bucket
    bucket = storage_client.get_bucket(bucket_name)
    
    #Blob: File name that will be saved.
    blob = bucket.get_blob('LAS.las')
    data_string = blob.download_as_string()
    print(data_string)
return data_string

【问题讨论】:

  • doesn't works是什么意思?
  • 如果你有文本文件然后data_string.split('\n')[:20] 你有 20 行。如果您有小文件,那么一次读取所有文件(只需要向服务器发出一个请求)然后逐行读取(可能需要向服务器发出许多请求)会更快。
  • 谢谢,我尝试添加此内容,但随后出现以下错误。我需要先转换它吗? data_split = data_string.split('\n')[:20] return data_split[0] line 35, in hello_world data_split = data_string.split('\n')[:20] TypeError: a bytes-like object is required,不是'str'
  • 也许它会提供字节数据,你必须在拆分 data_string.decode().split('\n')[:20] 之前 decode() 它。顺便说一句:如果你在return data_split[0] 中使用[0],那么你只会得到第一行。如果你需要 20 行,那么你需要 return data_split 而没有 [0]

标签: python arrays string google-cloud-functions google-cloud-storage


【解决方案1】:

如果您需要 20 行,则可以使用 .split('\n') 将字符串拆分为行,然后您可以使用 [:20] 获得 20 行。

似乎download_as_string() 给出了bytes,如果你想确保它使用utf-8 或ie,你必须使用decode()decode('utf-8') 将其转换为unicodedecode('cp1250') 如果你有文本编码 cp1250

blob = bucket.get_blob('LAS.las')
data_string = blob.download_as_string()

# convert bytes to unicode
data_string = data_string.decode()  

# convert string to list of lines
lines = data_string.split('\n')  

# return first 20 lines
return lines[:20]  

【讨论】:

  • 谢谢你,很遗憾,它没有用。我刚试了一下,得到了这个错误: data_string = data_string.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 2291: invalid start byte 这是否意味着我使用了错误的参数进行解码是吗?
  • 在 Google 中检查什么 char 可能有代码 0xb0 以及采用什么编码 - 也许它是 cp1250iso-8858(在 Windows 上都很流行)但 endoding 仅适用于原始文本文件,我第一次看到扩展名.las,不知道是不是文本文件。
  • python 文档codecs 中的更多编解码器但如果.las 不是原始文本文件而是压缩或具有特殊结构,则编码没有意义。
  • 谢谢,我去看看。我确实注意到,当它在存储桶中时,它在“类型”列下显示“应用程序/八位字节流”。这是否有助于弄清楚如何使用?
  • 它可以表示它不是文本文件,或者它是带有压缩文本的文件或以特殊方式保存的文本,您需要特殊的功能来从文件中提取文本。例如.txt之类的文件,您无需任何特殊方法即可阅读,但.doc.xls.pdf(也可能保留文本)如果没有特殊方法则无法阅读。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 2020-03-04
  • 2016-07-12
  • 2021-03-12
  • 2020-08-29
  • 1970-01-01
相关资源
最近更新 更多