0

what am I missing in this code (#instead of commented line in code) to have test.py file archived in zip folder ?

#!/usr/bin/python
import zipfile,os
path='/home/user/Desktop'

def zipdir(path, zipf):
  for file in os.walk(path):
    #zipf.write(os.path.join(root,path))




if __name__ == "__main__":

  zipf = zipfile.ZipFile('test.zip', 'w')
  zipdir(path, zipf)
  zipf.close()
3
  • 2
    stackoverflow.com/questions/1855095/… Commented Oct 12, 2015 at 10:54
  • @user1514631 why is in this question written root instead of path, inside os.path.join ? May You explain me this part ? Commented Oct 12, 2015 at 12:18
  • os.walk(path) returns a list of tuples, the first element of that tuple is the current directory (which some call root, and this changes as os.walk descends into the directories), by joining the current root with the current filename, you obtain the full pathname of the current file. The "variable" path in the linked answer is the starting directory where os.walk begins. To get a better understanding just print the root, dirs, files in your zipdir function, this way you will surely see what is happening. Commented Oct 12, 2015 at 13:27

1 Answer 1

1

The problem is that you're not unpacking all the variables returned by the os.walk() function, so you're telling the program to zip tuples and not paths. You have to make the following changes in the zipdir() function:

def zipdir(path, ziph):
    for root, dirs, files in os.walk(path):
        for file in files:
           ziph.write(os.path.join(root,file))

Check the following answer: How to create a zip archive of a directory

Sign up to request clarification or add additional context in comments.

2 Comments

why is in this answer (on link you provide me) written root instead of path, inside os.path.join ? May You explain me this part better, I dont understand?
Sorry, that comes from my code when I ran it my computer using different variables. The right expression is ziph.write(os.path.join(path, file)). This function basically builds the whole path to each of the files in the directory. os.walk() returns a tuple of three elements. The first is the whole path to the directory that is being listed, second the sub-directories inside the directory, and third the names of the files. To do the zip, you have to provide the whole path to each file, that's why you have to join the path to the directory (root) to the file. I fixed my answer ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.