5

I need to process some file generated from db objects and after required process need to delete that directory with files.I have decided to use python templefile package. I have give it a try but stuck on Direcotry not Empty [ Error 66 ].

In 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)
Aniket Pawar
  • 2,641
  • 19
  • 32
Abdul Rehman
  • 5,326
  • 9
  • 77
  • 150

1 Answers1

3

I'll just note that path = os.path.join(tmpdir) makes path equal to tmpdir. That said, when a directory is not empty, neither os.remove or os.rmdir will work.

Those are operating system calls, which don't recurse to files contained in the directory.

So just use

import shutil
shutil.rmtree(tmpdir)
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219