Python Learning: Automate Boring Stuff with Python | Chapter 8 : My Solution to Project: Backing Up a Folder into a Zip File

Just my solution to the project

I found the solution to the project provided in the book really good, but it zipped the entire folder structure in the absolute path. Something I am not pleased with. By adding the filepath base name to the zipfile.Zipfile.write() function, after the absolute file path (of the file to be written),  I was able to prevent that unnecessary folder zipping.

Code

# Backs up given file in a zip file and numbers accordingly
# Usage: python backupzip 

import sys
import os
import re
import zipfile

# TODO: get filepath
if len(sys.argv) == 2:
    filepath = sys.argv[1]
    filepath = os.path.abspath(filepath)
    # TODO: check if file path is valid
    if os.path.exists(filepath):
        # TODO: get list of files in the current directory
        backupNum = 1
        filepath_name = os.path.basename(filepath)
        filepath_name = filepath_name.split(".")
        regex_pattern = "^{}_\d+.zip$".format(filepath_name[0])
        regExp = re.compile(regex_pattern)
        for filename in os.listdir():
            # TODO: get number of files with filename
            match = regExp.match(filename)
            if match:
                backupNum += 1
        # TODO: create zipfile and zip filepath
        name = filepath_name[0] + "_" + str(backupNum) + ".zip"
        textZip = zipfile.ZipFile(name, "w")
        # TODO: walk through entire folder tree
        mainfolder = os.path.dirname(filepath)
        print("Main folder ", mainfolder)
        for dirpath, subfolders, files in os.walk(filepath):
            dirname = os.path.basename(dirpath)
            print("Adding files from {}".format(dirpath))
            # extract relative folder path
            [misc, relative_folder_path] = dirpath.split(mainfolder)
            newpath = os.path.join(relative_folder_path )
            print("New Path : {}".format(newpath))
            textZip.write(dirpath, newpath)
            for file in files:
                print(file)
                filp = os.path.join(dirpath, file)
                
                textZip.write(filp, os.path.join(relative_folder_path, file),
                              compress_type=zipfile.ZIP_DEFLATED)
        textZip.close()
    else:
        print("given file path does not exists")

else:
    print("Usage: python backupzip ")