python - 如何使用 Python 打开和处理存储在 Google Cloud Storage 中的 CSV 文件

标签 python google-app-engine google-cloud-storage

我使用的是 Google Cloud Storage 客户端库。

我正在尝试使用如下代码打开和处理 CSV 文件(已上传到存储桶):

filename = '/<my_bucket/data.csv'
with gcs.open(filename, 'r') as gcs_file:
    csv_reader = csv.reader(gcs_file, delimiter=',', quotechar='"')

我在响应 csv.reader 的第一个参数(即 gcs_file)时收到错误“参数 1 必须是迭代器”。显然 gcs_file 不支持迭代器 .next 方法。

关于如何进行的任何想法?我需要包装 gcs_file 并在其上创建迭代器还是有更简单的方法?

最佳答案

我认为你最好有自己的为 csv.reader 设计的包装器/迭代器。如果 gcs_file 支持 Iterator协议(protocol),不清楚 next() 应该返回什么以始终适应其消费者。

根据 csv 阅读器文档,它

Return a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable. If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

它需要来自底层文件的一大块原始字节,不一定是一行。你可以有这样的包装器(未测试):

class CsvIterator(object)
  def __init__(self, gcs_file, chunk_size):
     self.gcs_file = gcs_file
     self.chunk_size = chunk_size
  def __iter__(self):
     return self
  def next(self):
     result = self.gcs_file.read(size=self.chunk_size)
     if not result:
        raise StopIteration()
     return result

关键是一次读取一个 block ,这样当你有一个大文件时,你不会炸毁内存或遇到 urlfetch 超时。

或者更简单。使用 iter内置:

csv.reader(iter(gcs_file.readline, ''))

关于python - 如何使用 Python 打开和处理存储在 Google Cloud Storage 中的 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17841468/

相关文章:

java - GCS断点续传速度

google-cloud-storage - 使用 gsutil 执行 rsync 时公开文件

python-3.x - 在 PyPDF2 PdfFileReader 中使用 GCS 路径

python - assertRaises 没有捕捉到 IntegrityError ,Flask SQLAlchemy

python - 在 App Engine 的特定日期每小时安排一个 cron 作业执行

python - 如何将层次结构或多索引应用于 Pandas 列

python - 如何访问 Jinja2 模板(应用引擎上的 Bottle 框架)中的 session 数据?

google-app-engine - 今天的 App Engine 部署异常缓慢?

python - 不断在我的服务器上运行脚本

python - 如何在 pygame 中将数组可视化为线?