2017-07-24 35 views
-1

我需要處理一些從db對象生成的文件,並且在需要的過程之後需要使用文件刪除該目錄。我決定使用python templefile包。我給它一個嘗試,但停留在Direcotry not Empty [ Error 66 ].Python tempfile [Errno 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) 

回答

1

我就注意到path = os.path.join(tmpdir)使得path等於tmpdir。也就是說,當目錄不爲空時,os.removeos.rmdir都不起作用。

這些操作系統調用不會遞歸到目錄中包含的文件。

所以只使用

import shutil 
shutil.rmtree(tmpdir) 
相關問題