Python zipfile whole path is in file

99封情书 提交于 2019-12-25 01:22:34

问题


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

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