简体   繁体   中英

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?

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM