How can I add only a file to zip and not the folder path leading to it in Python?
python, syntax, zip
Solution
You need to look at `arcname` parameter of `ZipFile.write`:
`ZipFile.write(filename[, arcname[, compress_type]])`
Write the file named `filename` to the archive, giving it the archive name `arcname` (by default, this will be the same as `filename`, but without a drive letter and with leading path separators removed).
In your case, you most likely want:
zf.write(os.path.join(root, filename), filename, zipfile.ZIP_DEFLATED)
Problem
I'm using the code below to zip a backup file that is created daily. ``` import os, zipfile zf = zipfile.ZipFile("Test.zip", "w") for root, subdirs, files in os.walk("C:/Users/Bob/Desktop/Zip"): for filename in files: zf.write(os.path.join(root, filename)) zf.close() ``` The problem is that when I open the zip, it includes all the folders in the path leading to the file. For example, inside the zip, I would have a folder called Users/Bob/Desktop/Zip/File.gdb But I ONLY want the File.gdb inside the zip. The reason is because when it includes all these folders, it doesn't actually compress the file. It is the same size it is when it's not inside the zip. But if I only zip the File.gdb it does from 30Mb to 3Mb. Any help is appreciated.