0

I'm trying to write a zip file that contains a complete directory looking like this:

Aux
  rices
    rice with XYZ.txt
    rice with ABC.txt
  
  fruits
    fruit with ASD.txt
  
  meat
    chicken
       chicken with WER.txt
    beef
       beff with ASD.txt
  ...

I just want to compress the Aux folder with all the folders and txt files contained on it. However, I can only write the zipfile of the txt files, which are extracted from each directory.

The code I wrote is:

path = os.getcwd()
new_path = path + '/' + 'Aux'
new_title = 'new_book.zip'       

with zf.ZipFile(new_title, 'w') as zipObj:
     # Iterate over all the files in directory
     for folderName, subfolders, filenames in os.walk(new_path):
             for filename in filenames:
                 #create complete filepath of file in directory
                 filePath = os.path.join(folderName, filename)
                 # Add file to zip
                 zipObj.write(filePath, os.path.basename(filePath))

How would you do it?

Thanks

icatalan
  • 73
  • 4
  • 1
    Does this answer your question? [How to create a zip archive of a directory in Python?](https://stackoverflow.com/questions/1855095/how-to-create-a-zip-archive-of-a-directory-in-python) – Amit Nanaware Apr 16 '21 at 05:44
  • @AmitNanaware, unfortunatelly not. I tried these options before and didn't work to me. That's why I'm trying to get another answer. My error is in line ````filePath =...```` I think and this is the reason I only zip the txt files but I don't know how to solve it – icatalan Apr 16 '21 at 05:52
  • If you see the above example you can copy ziph.write as it is. If you see it it is writing the filepath, path and root of the file. – Amit Nanaware Apr 16 '21 at 06:04
  • Your question doesn't mention any error. If your code is producing an error, you should include the full stack trace in the question. – joao Apr 16 '21 at 07:22
  • @joao, I know, it doesn't mention any error because there isn't. But is a misfunction of what I want. That means, the function works well but not for my purpose. I am trying to learn how to modify my code. Thanks – icatalan Apr 16 '21 at 08:44
  • @AmitNanaware, you mean? ````for root, dirs, files in os.walk(path): for file in files: ziph.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.join(path, '..'))) ```` – icatalan Apr 16 '21 at 10:47

0 Answers0