如何在django中将zipfile作为File对象?

时间:2021-03-08 20:27:41

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.

我有一个名为'src'的文件夹,我创建了一个名为zf的zip文件。我想将zf作为FileField对象传递给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?

如何为zipfile做同样的事情?

1 个解决方案

#1


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?

这给了什么?

#1


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?

这给了什么?