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

使用Python加载本地CSV数据到BigQuery报错解决方案

核心报错原因

代码中配置的Google应用默认凭证环境变量名拼写错误:

  • Google Cloud SDK 识别的认证环境变量固定为GOOGLE_APPLICATION_CREDENTIALS(credential为复数形式,末尾带s)
  • 现有代码中写为GOOGLE_APPLICATION_CREDENTIAL,缺少末尾的s,SDK无法读取配置的服务账号密钥路径,直接触发认证失败。shell中如果配置的是同名错误变量,同样不会生效。
快速修复方案

直接修正环境变量名即可,修正后的代码如下:

from google.cloud import bigquery
import os

# 修正环境变量拼写,末尾加s
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = r"C:/Users/Pamungkas/Downloads/testing-353407-a3c774efeb5a.json"

client = bigquery.Client() 

table_id = "testing-353407.testing_field.sales"
file_path = r"C:\Users\Pamungkas\Downloads\sales.csv"

job_config = bigquery.LoadJobConfig(
    source_format=bigquery.SourceFormat.CSV,
    skip_leading_rows=1,
    autodetect=True,
    write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE
)

with open(file_path, "rb") as source_file:
    job = client.load_table_from_file(source_file, table_id, job_config=job_config)
    
job.result()

table = client.get_table(table_id)
print(
    "Loaded {} rows and {} columns to {}".format(
        table.num_rows, len(table.schema), table_id
    )
)
更稳定的推荐写法

不依赖环境变量,直接在代码中显式加载服务账号凭证,可以完全避免环境变量拼写错误、被其他逻辑覆盖的问题:

from google.cloud import bigquery
from google.oauth2 import service_account

# 直接加载服务账号密钥文件
credentials = service_account.Credentials.from_service_account_file(
    r"C:/Users/Pamungkas/Downloads/testing-353407-a3c774efeb5a.json"
)
# 初始化客户端时显式传入凭证和项目ID,避免SDK自动识别项目出错
client = bigquery.Client(credentials=credentials, project="testing-353407")

# 后续数据加载逻辑和之前一致
table_id = "testing-353407.testing_field.sales"
file_path = r"C:\Users\Pamungkas\Downloads\sales.csv"

job_config = bigquery.LoadJobConfig(
    source_format=bigquery.SourceFormat.CSV,
    skip_leading_rows=1,
    autodetect=True,
    write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE
)

with open(file_path, "rb") as source_file:
    job = client.load_table_from_file(source_file, table_id, job_config=job_config)
    
job.result()

table = client.get_table(table_id)
print(
    "Loaded {} rows and {} columns to {}".format(
        table.num_rows, len(table.schema), table_id
    )
)
后续校验点

如果修正后仍报错,按顺序排查:

  • 确认密钥文件路径填写正确,文件未损坏、未被其他程序占用
  • 密钥对应的服务账号已被授予必要权限:项目级BigQuery Job User角色、目标数据集testing_field级的BigQuery Data Editor角色
  • 本地安装的google-cloud-bigquery库版本过旧的话先升级,执行命令pip install --upgrade google-cloud-bigquery
  • 本地网络可正常访问Google Cloud API,未被防火墙、代理规则拦截请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 02:46:01