0

I have a problem with my zip file program where if I create a zip file, and it puts itself in the map of the files I want to zip, the program goes in a loop where the zip file keeps putting itself in it and the size of the file keeps growing until your computer starts to crash.

I have been looking for a while now but can't find a solution.

The real issue is that sometimes it does it and when I test it another time, it doesn't do it.

(Also in the def walk line it could give a fault, but it isn't)

    '''
    import tkinter as tk
    from tkinter import filedialog

    from pathlib import Path
    import zipfile
    import os

    import json
    import requests

    root = tk.Tk()
    root.withdraw()

    file_path = filedialog.askdirectory()

    os.chdir(file_path)

    def _walk(path: Path) -> []:
        all_files = []
        for x in path.iterdir():
            if x.is_dir():
                all_files.extend(_walk(x))
            else:
                all_files.append(x)
        return all_files


    def zip_files(path: Path, archive_name: str):
        all_files = _walk(path)
        with zipfile.ZipFile(f'{archive_name}', 'w', zipfile.ZIP_DEFLATED) as zipf:
            for f in all_files:
                zipf.write(f)
            zipf.close()


    def zip_this_folder():
        print('compressing...')
        zip_files(Path.cwd(), 'myzipfile.zip')
        print('...compression done!')


    if __name__ == "__main__":
        zip_this_folder()
    '''
MM-13
  • 32
  • 6

1 Answers1

0

Edit: The question was actually about how to not include the zipfile in itself. But the answer is even simpler then how not to include the script itself. Because the zipfile name is known, so then just the condition can be applied directly.

There are multiple ways how to find the name of the running script - see for example Get name of current script in Python

myscriptname = Path(__file__).name        #1
myscriptname = os.path.basename(__file__) #2
myscriptname = sys.argv[0]                #3  
print(myscriptname)

then add a condition

if x != myscriptname:
  all_files.append(x)
petrch
  • 1,807
  • 15
  • 19
  • I think I can use this in some way, but I can't see how this would solve my problem op the program creating a looped zip file. – MM-13 Nov 25 '21 at 19:07
  • ok, sorry, what about excluding the zipfile name instead? – petrch Nov 25 '21 at 22:32
  • That could be something, and what about excluding a subdirectory because I am already working with the directory of the files the program needs to compress? – MM-13 Nov 26 '21 at 07:12
  • well, feel free to exclude everything and everyone, but I think that if the problem is that you are including your zip file in your zip file it would be the best to exclude the zip file. – petrch Nov 26 '21 at 09:57
  • I know but would this be possible by using a subdirectory because I've been looking, found some things but don't really understand it? – MM-13 Nov 26 '21 at 11:58