How do i zip files in python without all directories written to it

泄露秘密 提交于 2020-03-03 08:40:10

问题


Im trying to zip multible files but i have run into a strange problem when i opened the zip file all directories leading to the files are listed as well home/site/Uploads/test/

Here is the python code i have written

import os
import zipfile

zf = zipfile.ZipFile("myzipfile.zip", "w")
for dirname, subdirs, files in os.walk("D:/home/site/Uploads/test/"):
zf.write(dirname)
for filename in files:
    zf.write(os.path.join(dirname, filename))
zf.close()

The zipped files are fine but why is every other directory listed too.

I got the zip file like this -->home-->site-->Uploads-->test-->file.txt what i wanted was this -->file.txt


回答1:


Lets assume the following directory structure:

./uploads
└── foo
    └── bar
        ├── 1.txt
        └── baz
            └── 2.txt

You just need to set the arcname correct:

import os
import zipfile

zf = zipfile.ZipFile("myzipfile.zip", "w")
for dirname, subdirs, files in os.walk("/tmp/uploads"):
    for filename in files:
        zf.write(os.path.join(dirname, filename), arcname=filename)
zf.close()

Unzip shows the zip file like this:

unzip -l myzipfile.zip                                                                                                                    Archive:  myzipfile.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  10-21-2019 15:03   1.txt
        0  10-21-2019 15:03   2.txt
---------                     -------
        0                     2 files


来源:https://stackoverflow.com/questions/58486174/how-do-i-zip-files-in-python-without-all-directories-written-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!