You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BigQuery Python API加载数据时如何保留ASCII控制字符

解决BigQuery Python API导入含ASCII控制字符CSV的问题

问题描述

尝试通过BigQuery Python API导入含ASCII控制字符的CSV文件时,加载任务失败,报错:

CSV file contains the ASCII 0 (NULL) character, you can't load the data into BigQuery.

已知通过bq命令行设置--preserve_ascii_control_characters=true可绕过此限制,但不清楚Python API的对应设置方法。

解决方案

BigQuery Python SDK的LoadJobConfig类中提供了对应的preserve_ascii_control_characters参数,直接设置为True即可允许加载含ASCII控制字符的CSV数据。

修改后的示例代码

import six
from google.cloud import bigquery

# 初始化BigQuery客户端
client = bigquery.Client()

# 替换为你的表ID
table_id = "your-project.your_dataset.your_table_name"

# 配置加载任务,启用保留ASCII控制字符
job_config = bigquery.LoadJobConfig(
    schema=[
        bigquery.SchemaField("name", "STRING"),
        bigquery.SchemaField("post_abbr", "STRING"),
    ],
    # 关键设置:允许保留ASCII控制字符
    preserve_ascii_control_characters=True
)

# 从本地文件加载示例
body = six.BytesIO(b"Washington,WA")
client.load_table_from_file(body, table_id, job_config=job_config).result()

# 从GCS加载的配置示例
job_config = bigquery.LoadJobConfig(
    write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE,
    source_format=bigquery.SourceFormat.CSV,
    skip_leading_rows=1,
    # 同样启用该参数
    preserve_ascii_control_characters=True
)

uri = "gs://cloud-samples-data/bigquery/us-states/us-states.csv"
load_job = client.load_table_from_uri(
    uri, table_id, job_config=job_config
)
load_job.result()

destination_table = client.get_table(table_id)
print(f"Loaded {destination_table.num_rows} rows.")

兼容旧版本SDK的补充方案

如果使用的SDK版本较旧,preserve_ascii_control_characters参数未直接暴露,可通过手动修改配置属性的方式添加:

# 在初始化job_config后添加
job_config._properties['load']['preserveAsciiControlCharacters'] = True

内容的提问来源于stack exchange,提问作者Thilina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 22:50:38