我使用的是 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/