Hulk Hulk - 1 year ago 140
Python Question

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':
dir = "/opt/files"
file_name = "%s/%s" % (dir,
form = UploadFileForm(request.POST, request.FILES)
handle_uploaded_file( file_name , file )

def handle_uploaded_file(file_name,f):
destination = open(file_name, 'wb+')
for chunk in f.chunks():

Answer Source

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

import os
from datetime import datetime
dirname ='%Y.%m.%d.%H.%M.%S') #2010. 
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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download