开发者

Create directory while upload using django

After uploading a file from the UI, how to create the a new directory with the current timestamp in /opt/files/ and copy the uploaded zip file to this directory, and unzip the zip file in the new directory and maintain the new directory name in a variable

def upload_info(request):
    if request.method == 'POST':
        file=request.FILES['file']
        dir = "/opt/files"
        file_name = "%s/%s" % (dir, file.name)
        form = UploadFileForm(request.POST, request.FILES)
        try:
            handle_uploaded_file( file_name , file )

def handle_uploaded_file(file_name,f):
    destination = open(file_name, 'wb+')
    for chunk in f.chunks开发者_JAVA百科():
        destination.write(chunk)
    destination.close()
    return


Creating a directory can be achieved using Python's os module (see documentation). For example:

import os
from datetime import datetime
dirname = datetime.now().strftime('%Y.%m.%d.%H.%M.%S') #2010.08.09.12.08.45 
os.mkdir(os.path.join('/opt/files', dirname))

You can use os.rename (documentation) to move the file as you choose (provided you have the necessary permissions). Unzipping can be done through the command line using Subprocesses or using a Python module (Examples using gzip module can be found here).


Here's a function I use:

def makedirs(path):
    try:
        os.makedirs(path)
    except OSError as e:
        if e.errno == 17:
            # Dir already exists. No biggie.
            pass


So, the correct answer for directory creation is:

If you want to create folders silently (if they don't exist):

import os
os.makedirs(exist_ok=True)

Throw an error if folder already exists:

import os
os.makedirs()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜