Sunday, August 19, 2018

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

Currently I use the following code:

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()

At the moment it creates a zip-file but the zip files contains the whole folder named 'data' that then contains the 'file.db'. How can I create a zip-file only contains 'file.db' and not the file in a folder?

Solved

I found that I get the right behavior via:

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()

No comments:

Post a Comment