将位于 google 云存储中的文本文件 (.txt) 转换为 CSV 文件?
convert text files(.txt) located in google cloud storage into CSV files?
我在云存储中有一组文本 (.txt) 文件(每 5 分钟上传到云存储中)。我想做的是将它们上传到大查询中。但是 bIgquery 不能接受文本文件。所以我必须把它转换成 Bq 可接受的格式。最好的方法是什么?
根据 this document,BigQuery 仅支持加载具有以下文件格式的数据:CSV、JSON、Avro 和 Google Cloud Datastore 备份。
因此,如果您将文本文件上传到 BigQuery,BigQuery 会将您的文本文件读取为 CSV 文件,然后确实会 运行 出错。
在将文本文件上传到 BigQuery 之前,您必须手动将其转换为 CSV 文件。
或者,您也可以 use Cloud Dataprep as it supports text files as inputs。您可以在 Dataprep 中对您的文本文件进行转换,然后将结果导出到 BigQuery。
这里有一个 Overview of Dataprep and a Quickstart Documentation 来学习如何使用它。
这是代码片段:
def getBlobAsString(bucketName, blobName):
storageClient = storage.Client()
bucket = storageClient.get_bucket(bucketName)
blobFile = bucket.get_blob(blobName)
blobStr = blobFile.download_as_string()
return(blobStr)
def getBlobAsFile(bucketName, blobName, txtStr):
storageClient = storage.Client()
csvFileName = blobName.replace('txt', 'csv')
bucket = storageClient.get_bucket(bucketName)
blob = bucket.blob(csvFileName)
blob.upload_from_string(txtStr)
return(csvFileName)
txtBucket = "bucket-name"
txtBlob = "blob-name"
# Read text file content as string
txtBlobAsStr = getBlobAsString(txtBucket, txtBlob)
txtStr = str(txtBlobAsStr, 'utf-8')
# Write text file content to CSV file
csvBlob = getBlobAsFile(txtBucket, txtBlob, txtStr)
我在云存储中有一组文本 (.txt) 文件(每 5 分钟上传到云存储中)。我想做的是将它们上传到大查询中。但是 bIgquery 不能接受文本文件。所以我必须把它转换成 Bq 可接受的格式。最好的方法是什么?
根据 this document,BigQuery 仅支持加载具有以下文件格式的数据:CSV、JSON、Avro 和 Google Cloud Datastore 备份。
因此,如果您将文本文件上传到 BigQuery,BigQuery 会将您的文本文件读取为 CSV 文件,然后确实会 运行 出错。
在将文本文件上传到 BigQuery 之前,您必须手动将其转换为 CSV 文件。
或者,您也可以 use Cloud Dataprep as it supports text files as inputs。您可以在 Dataprep 中对您的文本文件进行转换,然后将结果导出到 BigQuery。
这里有一个 Overview of Dataprep and a Quickstart Documentation 来学习如何使用它。
这是代码片段:
def getBlobAsString(bucketName, blobName):
storageClient = storage.Client()
bucket = storageClient.get_bucket(bucketName)
blobFile = bucket.get_blob(blobName)
blobStr = blobFile.download_as_string()
return(blobStr)
def getBlobAsFile(bucketName, blobName, txtStr):
storageClient = storage.Client()
csvFileName = blobName.replace('txt', 'csv')
bucket = storageClient.get_bucket(bucketName)
blob = bucket.blob(csvFileName)
blob.upload_from_string(txtStr)
return(csvFileName)
txtBucket = "bucket-name"
txtBlob = "blob-name"
# Read text file content as string
txtBlobAsStr = getBlobAsString(txtBucket, txtBlob)
txtStr = str(txtBlobAsStr, 'utf-8')
# Write text file content to CSV file
csvBlob = getBlobAsFile(txtBucket, txtBlob, txtStr)