【发布时间】:2019-12-16 21:22:46
【问题描述】:
我正在编写一个小型云函数 python 脚本来重写来自存储的 csv 文件(跳过一些列)并将其发送到 BigQuery。
我的脚本的 BigQuery 部分是这样的:
def bq_import(request):
job_config.skip_leading_rows = 1
# The source format defaults to CSV, so the line below is optional.
job_config.source_format = bigquery.SourceFormat.CSV
uri = "gs://url.appspot.com/fil.csv"
load_job = bq_client.load_table_from_uri(
uri, dataset_ref.table('table'), job_config=job_config
) # API request
load_job.result() # Waits for table load to complete.
destination_table = bq_client.get_table(dataset_ref.table('table'))
我发现这个脚本允许我通过跳过一些列来重写 csv:
def remove_csv_columns(input_csv, output_csv, exclude_column_indices):
with open(input_csv) as file_in, open(output_csv, 'w') as file_out:
reader = csv.reader(file_in)
writer = csv.writer(file_out)
writer.writerows(
[col for idx, col in enumerate(row)
if idx not in exclude_column_indices]
for row in reader)
remove_csv_columns('in.csv', 'out.csv', (3, 4))
所以我基本上需要让这两个脚本在我的云功能中协同工作。但是我不确定我应该如何处理remove_csv_columns 函数,尤其是output_csv 变量。我应该创建一个空的虚拟 csv 文件吗?还是一个数组或类似的东西?如何即时重写此 csv 文件?
我认为我的最终脚本应该是这样的,但缺少一些东西......
uri = "gs://url.appspot.com/fil.csv"
def remove_csv_columns(uri, output_csv, exclude_column_indices):
with open(input_csv) as file_in, open(output_csv, 'w') as file_out:
reader = csv.reader(file_in)
writer = csv.writer(file_out)
writer.writerows(
[col for idx, col in enumerate(row)
if idx not in exclude_column_indices]
for row in reader)
def bq_import(request):
job_config.skip_leading_rows = 1
# The source format defaults to CSV, so the line below is optional.
job_config.source_format = bigquery.SourceFormat.CSV
csv_file = remove_csv_columns('in.csv', 'out.csv', (3, 4))
load_job = bq_client.load_table_from_uri(
csv_file, dataset_ref.table('table'), job_config=job_config
) # API request
load_job.result() # Waits for table load to complete.
destination_table = bq_client.get_table(dataset_ref.table('table'))
基本上我认为我需要通过remove_csv_columns 在 bq_import 函数中定义我的 cvs 文件,但我不确定如何。
顺便说一句,我正在学习 python,但我不是开发专家。谢谢。
【问题讨论】:
-
您的文件大小是多少?
标签: python python-3.x google-cloud-functions