The zipfile write() method supports an extra argument (arcname) which is the archive name to be stored in the zip file, so you would only need to change your code with:

from os.path import basename
...
zip.write(first_path, basename(first_path))
zip.write(second_path, basename(second_path))
zip.close()

When you have some spare time reading the documentation for zipfile will be helpful.

Answer from João Pinto on Stack Overflow
🌐
Python
docs.python.org › 3 › library › zipfile.html
zipfile — Work with ZIP archives
February 23, 2026 - ... Extract a member from the archive to the current working directory; member must be its full name or a ZipInfo object. Its file information is extracted as accurately as possible. path specifies a different directory to extract to.
🌐
Real Python
realpython.com › python-zipfile
Python's zipfile: Manipulate Your ZIP Files Efficiently – Real Python
January 26, 2025 - In the python-zipfile/ directory, you have a subdirectory called source_dir/, with the following content: source_dir/ │ ├── hello.txt ├── lorem.md └── realpython.md · In source_dir/, you only have three regular files. Because the directory doesn’t contain subdirectories, you can use pathlib.Path.iterdir() to iterate over its content directly.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Zip and Unzip Files in Python: zipfile, shutil | note.nkmk.me
August 13, 2023 - zipfile - ZipFile Objects — Work with ZIP archives — Python 3.11.4 documentation · The constructor zipfile.ZipFile(file, mode, ...) is used to create ZipFile objects. Here, file represents the path of a ZIP file, and mode can be 'r' for read, 'w' for write, or 'a' for append.
🌐
GeeksforGeeks
geeksforgeeks.org › working-zip-files-python
Working with zip files in Python - GeeksforGeeks
July 22, 2021 - 2. Writing to a zip file Consider a directory (folder) with such a format: Here, we will need to crawl the whole directory and its sub-directories in order to get a list of all file paths before writing them to a zip file. The following program does this by crawling the directory to be zipped: ... # importing required modules from zipfile import ZipFile import os def get_all_file_paths(directory): # initializing empty file paths list file_paths = [] # crawling through directory and subdirectories for root, directories, files in os.walk(directory): for filename in files: # join the two strings in order to form the full filepath.
🌐
Python Module of the Week
pymotw.com › 2 › zipfile
zipfile – Read and write ZIP archive files - Python Module of the Week
Since version 2.3 Python has had the ability to import modules from inside ZIP archives if those archives appear in sys.path. The PyZipFile class can be used to construct a module suitable for use in this way. When you use the extra method writepy(), PyZipFile scans a directory for .py files and adds the corresponding .pyo or .pyc file to the archive. If neither compiled form exists, a .pyc file is created and added. import sys import zipfile if __name__ == '__main__': zf = zipfile.PyZipFile('zipfile_pyzipfile.zip', mode='w') try: zf.debug = 3 print 'Adding python files' zf.writepy('.') finally: zf.close() for name in zf.namelist(): print name print sys.path.insert(0, 'zipfile_pyzipfile.zip') import zipfile_pyzipfile print 'Imported from:', zipfile_pyzipfile.__file__
🌐
PythonAnywhere
pythonanywhere.com › forums › topic › 13794
How to access a folder in a zip file? : Forums : PythonAnywhere
January 19, 2019 - you should probably use the full path if you are worried about path issues. but it should look like /home/name/tutorial/prof/ks.zip/ instead of home/name/tutorial/prof/ks.zip/ conrad | 4232 posts | PythonAnywhere staff | Jan. 20, 2019, 12:07 p.m. | permalink · Hi Conrad, thks for formatting the code (how did you do that?). So you mean · ::: # specifying the zip file name · file_name = "/home/name/tutorial/prof/ks.zip/" # opening the zip file in READ mode · with ZipFile(file_name, 'r') as zip: # printing all the contents of the zip file ·
🌐
Guru99
guru99.com › home › python › python zip file with example
Python ZIP file with Example
August 12, 2024 - import os import shutil from zipfile import ZipFile from os import path from shutil import make_archive # Check if file exists if path.exists("guru99.txt"): # get the path to the file in the current directory src = path.realpath("guru99.txt"); # rename the original file os.rename("career.guru99.txt","guru99.txt") # now put things into a ZIP archive root_dir,tail = path.split(src) shutil.make_archive("guru99 archive","zip",root_dir) # more fine-grained control over ZIP files with ZipFile("testguru99.zip", "w") as newzip: newzip.write("guru99.txt") newzip.write("guru99.txt.bak")
Find elsewhere
🌐
Stack Abuse
stackabuse.com › creating-a-zip-archive-of-a-directory-in-python
Creating a Zip Archive of a Directory in Python
September 14, 2023 - Python's standard library comes with a module named zipfile that provides methods for creating, reading, writing, appending, and listing contents of a ZIP file. This module is useful for creating a zip archive of a directory. We'll start by importing the zipfile and os modules: ... def zip_directory(directory_path, zip_path): with zipfile.ZipFile(zip_path, 'w') as zipf: for root, dirs, files in os.walk(directory_path): for file in files: zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.join(directory_path, '..')))
Top answer
1 of 4
11

As shown in: Python: Getting files into an archive without the directory?

The solution is:

     ''' 
    zip_file:
        @src: Iterable object containing one or more element
        @dst: filename (path/filename if needed)
        @arcname: Iterable object containing the names we want to give to the elements in the archive (has to correspond to src) 
'''
def zip_files(src, dst, arcname=None):
    zip_ = zipfile.ZipFile(dst, 'w')

    print src, dst
    for i in range(len(src)):
        if arcname is None:
            zip_.write(src[i], os.path.basename(src[i]), compress_type = zipfile.ZIP_DEFLATED)
        else:
            zip_.write(src[i], arcname[i], compress_type = zipfile.ZIP_DEFLATED)

    zip_.close()
2 of 4
5
import os
import zipfile

def zipdir(src, dst, zip_name):
    """
    Function creates zip archive from src in dst location. The name of archive is zip_name.
    :param src: Path to directory to be archived.
    :param dst: Path where archived dir will be stored.
    :param zip_name: The name of the archive.
    :return: None
    """
    ### destination directory
    os.chdir(dst)
    ### zipfile handler
    ziph = zipfile.ZipFile(zip_name, 'w')
    ### writing content of src directory to the archive
    for root, dirs, files in os.walk(src):
        for file in files:
            ### In this case the structure of zip archive will be:
            ###       C:\Users\BO\Desktop\20200307.zip\Audacity\<content of Audacity dir>
            # ziph.write(os.path.join(root, file), arcname=os.path.join(root.replace(os.path.split(src)[0], ""), file))

            ### In this case the structure of zip archive will be:
            ###       C:\Users\BO\Desktop\20200307.zip\<content of Audacity dir>
            ziph.write(os.path.join(root, file), arcname=os.path.join(root.replace(src, ""), file))
    ziph.close()


if __name__ == '__main__':
    zipdir("C:/Users/BO/Documents/Audacity", "C:/Users/BO/Desktop", "20200307.zip")
🌐
SQLPad
sqlpad.io › tutorial › python-zipfile
Python zipfile | SQLPad
April 29, 2024 - The zipfile module in Python provides a straightforward method for extracting files from a zip archive. Whether you need to retrieve a single file or the entire contents, the module equips you with the tools to accomplish the task with ease. Let's dive into the practical aspects of extracting files from a zip archive. To extract all files from a zip archive, you can use the extractall() method. Here's a simple example: import zipfile # Specify the path to your zip file zip_path = 'example.zip' # Specify the directory to extract to extract_to_dir = 'extracted_content/' # Open the zip file in read mode with zipfile.ZipFile(zip_path, 'r') as zip_ref: # Extract all contents into the specified directory zip_ref.extractall(extract_to_dir) print(f"All files extracted to {extract_to_dir}")
🌐
Linux Hint
linuxhint.com › python_zip_file
Python Zip File
In this line of code, we have imported the ZipFile class from the zipfile module. The ZipFile class is used to write the ZIP file. We do not need to use the other classes of zipfile for creating a ZIP file. #specifying the path of files myfiles = ['/home/linuxhint/Documents/myfile.txt', '/home/linuxhint/Documents/myfile1.txt']
Published   November 25, 2020
🌐
GitHub
github.com › python › cpython › issues › 99818
zipfile.Path is not Path-like · Issue #99818 · python/cpython
November 27, 2022 - This is about zipfile.Path. The doc says it is compatible to pathlib.Path. But it seems that is not for 100% because it doesn't derive from pathlib.PurePath and can treated as Path-like in all ...
Author   buhtz
🌐
Readthedocs
zipp.readthedocs.io
zipp 3.23.2.dev6+g624092f53 documentation
Implements many of the features users enjoy from pathlib.Path. ... >>> data = io.BytesIO() >>> zf = zipfile.ZipFile(data, 'w') >>> zf.writestr('a.txt', 'content of a') >>> zf.writestr('b/c.txt', 'content of c') >>> zf.writestr('b/d/e.txt', 'content of e') >>> zf.filename = 'mem/abcde.zip'
🌐
DataCamp
datacamp.com › tutorial › zip-file
Python zipfile: Zip, Extract, Read & Create Zip Files | DataCamp
November 29, 2018 - In this tutorial, you are going to learn how to work with Zip Files in Python using the zipfile module.