如何在不添加文件夹的情况下将文件压缩到 Python?

How do I zip a file in Python without adding folders?

目前我使用以下代码:

import zipfile

root_path = 'C:/data/'

def zipping_sql_database():
    zf = zipfile.ZipFile(root_path + 'file.zip', mode='w')
    try:
        zf.write(root_path + "file.db")
    finally:
        zf.close()

目前它创建了一个 zip 文件,但 zip 文件包含名为 'data' 的整个文件夹,然后包含 'file.db'。如何创建一个仅包含 'file.db' 而不是文件夹中的文件的 zip 文件?

我发现我通过以下方式获得了正确的行为:

import zipfile

root_path = 'C:/data/'

def zipping_sql_database():
    zf = zipfile.ZipFile(root_path + 'file.zip', mode='w')
    try:
        zf.write(root_path + "file.db", "file.db")
    finally:
        zf.close()