Python tempfile [Errno 66] Directory not empty
本问题已经有最佳答案,请猛点这里访问。
我需要处理一些从数据库对象生成的文件,在需要处理之后,需要用文件删除该目录。我已经决定使用python templefile包。我试过了,但还是坚持住了。
在VIEW中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 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 2 | import shutil shutil.rmtree(tmpdir) |