I'm using python's zipfile
module.
Having a zip file located in a path of:/home/user/a/b/c/test.zip
And having another file created under /home/user/a/b/c/1.txt
I want to add this file to existing zip, I did:
zip = zipfile.ZipFile('/home/user/a/b/c/test.zip','a') zip.write('/home/user/a/b/c/1.txt') zip.close()`
And got all the subfolders appears in path when unzipping the file, how do I just enter the zip file without path's subfolders?
I tried also : zip.write(os.path.basename('/home/user/a/b/c/1.txt'))
And got an error that file doesn't exist, although it does.
The simplest way to add a file to an already existing archive is the ' --append ' (' -r ') operation, which writes specified files into the archive whether or not they are already among the archived files. When you use ' --append ', you must specify file name arguments, as there is no default.
Sometimes it's easy to delete a ZIP file and create a new one – say you've forgotten to include a file. Just drag it into the folder to be ZIPped up and start again.
You got very close:
zip.write(path_to_file, os.path.basename(path_to_file))
should do the trick for you.
Explanation: The zip.write
function accepts a second argument (the arcname) which is the filename to be stored in the zip archive, see the documentation for zipfile more details.
os.path.basename()
strips off the directories in the path for you, so that the file will be stored in the archive under just it's name.
Note that if you only zip.write(os.path.basename(path_to_file))
it will look for the file in the current directory where it (as the error says) does not exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With