Search code examples
pythonzip

zip folder using python without changing directory


I want to zip a folder at x location to y location, I have written code for it. This is my code -

cwd = os.getcwd()
os.chdir(path.realpath(f"/y"))
shutil.make_archive(filename, "zip", file_path)
os.chdir(cwd)

I don't want to change directories, can I pass path of the folder I want to zip and path of the destination where I want to store that zipped folder? is this possible using python ?


Solution

  • If you wanted to archive /location/x/my_folder to /location/y/my_archive.zip:

    The base_name is describing the destination, in this case location y.

    The combination of root_dir and base_dir describe the source, in this case x.

    The base_dir is the directory that gets added to the archive.

    from shutil import make_archive
    root_dir = "/location/x"
    
    make_archive(base_name="/location/y/my_archive",
                 format="zip",
                 root_dir=root_dir,
                 base_dir="my_folder")