2

I have a folder named 'src' of which I create a zip file named zf. I want to pass zf as a FileField object to newobj.fd.

import zipfile
from django.core.files import File

f='s1.zip'
zf = zipfile.ZipFile(f, "w")
for dirname, subdirs, files in os.walk(src):
    zf.write(dirname)
    for filename in files:
        zf.write(os.path.join(dirname, filename))
        zf.open(os.path.join(dirname, filename))
newobj.fd= File(zf)

I do this thing for a text file and it works:

f=file('text.txt')
newobj.fd2=File(f)
f.close()

How do the same thing for a zipfile?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sam
  • 113
  • 1
  • 1
  • 9

1 Answers1

0
import zipfile
from django.core.files import File

f='s1.zip'
zf = zipfile.ZipFile(f, "w")
for dirname, subdirs, files in os.walk(src):
    zf.write(dirname)
    for filename in files:
        zf.write(os.path.join(dirname, filename))
zf.close()
newobj.fd = File(f)

What does this give?

Dharman
  • 30,962
  • 25
  • 85
  • 135
joel goldstick
  • 4,393
  • 6
  • 30
  • 46
  • I did this after trying your answer but it gives the error: I/O operation on closed file. I removed zf.close() but the error still persists. – Sam Mar 13 '16 at 20:42
  • Give the complete traceback (copy and paste). Are you sure the newobj.fd = code is outdented properly? – joel goldstick Mar 13 '16 at 21:25
  • I removed zf.close() and replaced it with zf.open(os.path.join(dirname, filename)). The problem now is that even though there is no error popping up but the zip file is not getting copied to the required location. On the other hand, the text file is getting copied properly. – Sam Mar 13 '16 at 21:45
  • I changed my answer. I moved the close out of the loop. It closed after adding first file. What is newobj? – joel goldstick Mar 13 '16 at 23:20
  • It still gives the error: I/O operation on closed file – Sam Mar 13 '16 at 23:29
  • can you copy the traceback to your question. what line does it point to? – joel goldstick Mar 13 '16 at 23:32