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

Github Action创建kaggle.json提示目录不存在的解决方法

解决Github Action中Kaggle数据集下载的FileNotFoundError问题

问题根源

报错是因为Github Action的Ubuntu运行环境中,/home/runner/.kaggle目录默认不存在,而Python的open函数w+模式仅能创建文件,无法自动生成上级目录,导致写入失败。

解决方案

方案1:在Python代码中自动创建目录

修改代码,先检查并创建目标目录,再写入文件,同时设置Kaggle要求的文件权限(必须为600,否则后续调用Kaggle API会报错):

import os
import os.path

json_str = '{"username":"headwater","key":"My key"}'
if is_64bit_ubuntu():
    kaggle_dir = '/home/runner/.kaggle'
    # 创建目录,exist_ok=True避免目录已存在时报错
    os.makedirs(kaggle_dir, exist_ok=True)
    json_path = os.path.join(kaggle_dir, 'kaggle.json')
    with open(json_path, 'w+') as fp:
        fp.write(json_str)
    # 设置文件权限为600
    os.chmod(json_path, 0o600)
elif is_windows():
    kaggle_dir = 'C:\\Users\\runneradmin\\.kaggle'
    os.makedirs(kaggle_dir, exist_ok=True)
    json_path = os.path.join(kaggle_dir, 'kaggle.json')
    with open(json_path, 'w+') as fp:
        fp.write(json_str)
    os.chmod(json_path, 0o600)

方案2:在Github Action流程中提前创建目录

如果不想修改Python代码,可以在Github Action的YAML配置文件中,添加单独步骤创建目录并设置权限,再执行脚本:

jobs:
  download-kaggle-data:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
      
      # 提前创建.kaggle目录
      - name: Create Kaggle directory
        run: mkdir -p /home/runner/.kaggle
      
      # 执行你的Python脚本
      - name: Run dataset download script
        run: python your_script.py
      
      # 设置kaggle.json权限(如果脚本里没处理)
      - name: Set Kaggle config permissions
        run: chmod 600 /home/runner/.kaggle/kaggle.json

额外提示

建议不要在代码中硬编码Kaggle的username和key,而是通过Github Action的机密变量传递,避免敏感信息泄露:

  1. 在Github仓库的「Settings」→「Secrets and variables」→「Actions」中添加KAGGLE_USERNAME和KAGGLE_KEY两个机密变量。
  2. 修改Python代码读取环境变量:
import os

json_str = f'{{"username":"{os.getenv("KAGGLE_USERNAME")}","key":"{os.getenv("KAGGLE_KEY")}"}}'
# 后续创建目录、写入文件的逻辑不变
  1. 在Github Action的YAML中传递变量:
- name: Run dataset download script
  run: python your_script.py
  env:
    KAGGLE_USERNAME: ${{ secrets.KAGGLE_USERNAME }}
    KAGGLE_KEY: ${{ secrets.KAGGLE_KEY }}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:43:11