0

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))
Dharman
  • 30,962
  • 25
  • 85
  • 135
user2290362
  • 717
  • 2
  • 7
  • 21

1 Answers1

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.

mhawke
  • 84,695
  • 9
  • 117
  • 138
  • Thanks for the answer, but I need to preserve the file structure. I essentially want to pass an absolute path for the directory and the program to just make a zip file exactly the same as the contents of that directory, with nothing else. Is that possible? – user2290362 Dec 15 '14 at 12:53
  • @user2290362 - yes, that's the bit that was unclear. See updated answer. – mhawke Dec 15 '14 at 14:08