Adding a file to an existing zip file

I am using the Python zipfile module.
The presence of a zip file in the path:
/home/user/a/b/c/test.zip
And, having another file created in /home/user/a/b/c/1.txt I want to add this file to an 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 appearing in the path when unzipping the file, how can I just enter the zip file without the path subfolders?

I also tried: zip.write(os.path.basename('/home/user/a/b/c/1.txt')) and got the error that the file does not exist, although it does exist.

+8
source share
2 answers

You are 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 the second argument (arc name), which is the name of the file to be stored in the zip archive, see the documentation for zipfile for details.

os.path.basename() removes directories in the path for you, so the file will be stored in the archive under its name.

Please 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.

+12
source
 import zipfile # Open a zip file at the given filepath. If it doesn't exist, create one. # If the directory does not exist, it fails with FileNotFoundError filepath = '/home/user/a/b/c/test.zip' with zipfile.ZipFile(filepath, 'a') as zipf: # Add a file located at the source_path to the destination within the zip # file. It will overwrite existing files if the names collide, but it # will give a warning source_path = '/home/user/a/b/c/1.txt' destination = 'foobar.txt' zipf.write(source_path, destination) 
0
source

Source: https://habr.com/ru/post/1238145/


All Articles