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

Python创建临时目录写入文件报PermissionError权限错误问题

问题根因

你代码中直接将tempfile.TemporaryDirectory()生成的临时目录路径作为文件路径传入open()方法尝试写入,操作系统禁止直接对目录对象执行写文件操作,返回的错误被封装为PermissionError,并非临时目录本身没有读写权限,属于操作对象类型错误。

修复方案

需要先在临时目录下拼接你要写入的具体文件的完整路径,再对该文件执行写入操作,推荐使用上下文管理器管理临时目录,退出作用域时会自动删除,无需手动清理。

完整示例代码如下:

import os
import tempfile
import subprocess

# 上下文管理器自动管理临时目录生命周期
with tempfile.TemporaryDirectory() as temp_dir:
    # 拼接构建脚本的完整路径
    build_script_path = os.path.join(temp_dir, "build.sh")
    # 写入脚本内容
    with open(build_script_path, "w", encoding="utf-8", newline="\n") as f:
        f.write("#!/bin/bash\n")
        f.write("echo docker build test\n")
        # 补充其他需要的脚本逻辑
    
    # 写入Dockerfile(可根据需求调整)
    dockerfile_path = os.path.join(temp_dir, "Dockerfile")
    with open(dockerfile_path, "w", encoding="utf-8") as f:
        f.write("FROM alpine:latest\n")
        f.write("COPY build.sh /app/\n")
        f.write("RUN chmod +x /app/build.sh\n")
        f.write("CMD [\"/app/build.sh\"]\n")
    
    # 执行docker构建,上下文指定为临时目录
    subprocess.run(
        ["docker", "build", "-t", "my-custom-image", "."],
        cwd=temp_dir,
        check=True
    )
# 临时目录在此处已自动删除
注意事项
  • Windows平台编写Linux容器使用的.sh脚本时,指定newline="\n"可避免生成Windows格式的CRLF换行符,防止脚本执行报错
  • 脚本的执行权限建议在Dockerfile中通过RUN chmod +x配置,无需在宿主系统修改
  • 如果不使用上下文管理器管理TemporaryDirectory,需手动调用temp_dir.cleanup()方法删除临时目录,避免磁盘残留

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:54:00