问题
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