问题
I'm using the code from here to make a zip file from a directory. I give the function an absolute path to a folder from a GUI. Currently, say the path is c:\users......, the zip folder structure is users...... .
How can I remove the absolute path bits and just have the end folder of the path being used for the zip file? I understand that the result is right, because what I'm describing is the result from os.walk but I want to strip out the absolute path.
def zipdir(path, zip):
for root, dirs, files in os.walk(path):
for file in files:
zip.write(os.path.join(root, file))
回答1:
Do this:
def zipdir(path, zip):
path = os.path.abspath(path)
for root, dirs, files in os.walk(path):
dest_dir = root.replace(os.path.dirname(path), '', 1)
for file in files:
zip.write(os.path.join(root, file), arcname=os.path.join(dest_dir, file))
This converts the given path
to an absolute path, the directory name of which is used to remove the leading path component in root
.
来源:https://stackoverflow.com/questions/27483431/python-zipfile-whole-path-is-in-file