Python 临时文件 [Errno 66] 目录不为空

标签 python django python-3.x django-views

我需要处理从数据库对象生成的一些文件,并且在所需的处理之后需要删除该目录的文件。我决定使用 python Templefile 包。我已经尝试过,但坚持 Direcotry not Empty [ Error 66 ].

views.py

def writeFiles(request, name):
    tmpdir = tempfile.mkdtemp()
    instance = request.user.instances.get(name=name)
    print(instance)
    print(instance.name)
    code = instance.serverFile
    jsonFile = instance.jsonPackageFile
    docker = """
    FROM node
    # Create app directory
    RUN mkdir -p /usr/src/app
    WORKDIR /usr/src/ap

    # Install app dependencies
    COPY package.json /usr/src/app/
    RUN npm install

    # Bundle app source
    COPY . /usr/src/app

    EXPOSE 8080
    CMD [ "node", "server" ]"""
    # Ensure the file is read/write by the creator only
    saved_umask = os.umask(0o077)
    server = 'server.js'
    json = 'package.json'
    path = os.path.join(tmpdir)
    print(path)
    try:
        with open(path + '/dockerfile', "w") as dockerfile:
            dockerfile.write(docker)
        with open(path + '/server.js', "w") as server:
            server.write(code)
        with open(path + 'package.json', "w") as json:
            json.write(jsonFile)
        print(os.path.join(tmpdir, json))
    except IOError as e:
        print('IOError:', e)
    else:
        os.remove(path)
    finally:
        os.umask(saved_umask)
        os.rmdir(tmpdir)

最佳答案

我只是注意到,path = os.path.join(tmpdir) 使path 等于tmpdir。也就是说,当目录不为空时,os.removeos.rmdir 都不起作用。

这些是操作系统调用,不会递归到目录中包含的文件。

所以只需使用

import shutil
shutil.rmtree(tmpdir)

关于Python 临时文件 [Errno 66] 目录不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45274867/

相关文章:

python - 在 python3 字节对象中测试 ASCII 字符的最佳方法

python - 基于类字段的生成函数?

python - 如何确定通过 `from m import *` 导入的内容?

python-3.x - 如何在Python的scipy信号卷积中添加比率参数?

Python:如何测试潜在的变量名称是否在命名空间中?

python - 在 Django 中声明 DB 字段时,verbose_name 参数中的非 ASCII 字符串

python - Django-dbbackup : how to change backup file extension?

javascript - Django 模板 : insert values for javascript variables

python - 基于多列对 DataFrame 进行排名

python - 如何在postman的Body中输入两个input