Python读写本地JSON文件在GitHub Actions执行时异常的问题求助
解决GitHub Actions中Python脚本读写JSON文件的路径问题
问题根源
GitHub Actions Runner的默认工作目录是仓库根目录,但如果你的脚本不在根目录,直接用相对路径example.json会指向根目录而非脚本所在目录,导致读不到文件;写入时虽然没报错,但文件可能写到了根目录(或者Runner临时目录,跑完就被自动清理),所以你找不到。
脚本修改方案
用os模块获取脚本所在的绝对路径,确保无论工作目录在哪,都能准确定位到JSON文件:
import json import os # 获取当前脚本所在的绝对目录 script_dir = os.path.dirname(os.path.abspath(__file__)) # 拼接JSON文件的完整路径 json_file_path = os.path.join(script_dir, 'example.json') # 读取JSON文件(改用with语句更安全,避免文件句柄泄漏) with open(json_file_path, 'r', encoding='utf-8') as infile: existing_file = json.load(infile) # 写入更新后的JSON文件 with open(json_file_path, 'w', encoding='utf-8') as outfile: json.dump({}, outfile, indent=2) # indent可选,让输出JSON格式更美观
Workflow配置检查
- 确保已拉取代码:Workflow里必须包含
actions/checkout步骤,否则Runner里没有你的代码文件:
steps: - name: Checkout code uses: actions/checkout@v4
- 确认运行脚本的工作目录:如果脚本在子目录(比如
scripts/),运行脚本时要么切换到该目录,要么用完整路径调用:
steps: - name: Run Python script working-directory: ./scripts # 如果脚本在scripts目录下,设置工作目录 run: python your_script.py # 或者不用working-directory,直接写:python scripts/your_script.py
- 保留输出文件:如果需要在Workflow结束后拿到更新后的JSON文件,要添加
upload-artifact步骤,否则Runner销毁后文件就会丢失:
steps: - name: Upload updated JSON file uses: actions/upload-artifact@v4 with: name: updated-example-json path: scripts/example.json # 替换成你的JSON文件实际路径
额外注意事项
- 读取/写入文件时指定编码
encoding='utf-8',避免不同环境下的编码兼容问题; - 用
json.dump()替代json.dumps()直接写入文件,更高效且避免额外的字符串处理步骤。
内容的提问来源于stack exchange,提问作者jros
相关产品推荐
相关产品推荐

