Friday, 29 November 2024

FPP Assignment no 11 Backing up a given file.


Problem Statement: Develop a program to backing Up a given Folder (Folder in a current working directory) into a ZIP File by using relevant modules and suitable methods.


Program Implementation:


import os

import zipfile

from datetime import datetime


def backup_to_zip(folder):

    # Ensure the folder path is absolute

"""

An absolute path is a full path that specifies the location of a file or directory from the root directory (‘/’). It provides a complete address that points directly to a file or directory, regardless of the current working directory.

"""

    folder = os.path.abspath(folder)

    

    # Generate a unique filename for the ZIP file

    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

    zip_filename = f"{os.path.basename(folder)}_backup_{timestamp}.zip"

    

    print (f"Creating backup ZIP file: {zip_filename}")

    

    # Create the ZIP file

    with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as backup_zip:

        # Walk through the folder and add files to the ZIP

        for foldername, subfolders, filenames in os.walk(folder):

            print (f"Adding folder: {foldername}")

            # Add the current folder to the ZIP

            backup_zip.write(foldername, os.path.relpath(foldername, folder))

 """

relative path specifies the location of a file or directory in relation to the current working directory (often abbreviated as pwd). It does not start with a slash (‘/’), and it utilizes navigational shortcuts to refer to the file or directory.

"""

            # Add all files in this folder to the ZIP

            for filename in filenames:

                file_path = os.path.join(foldername, filename)

                arcname = os.path.relpath(file_path, folder)

                print (f"Adding file: {file_path}")

                backup_zip.write(file_path, arcname)

    

    print (f"Backup completed successfully! Saved as {zip_filename}")


# Example Usage

if __name__ == "__main__":

    folder_to_backup = input ("Enter the folder name to back up: ")

    if os.path.exists(folder_to_backup) and os.path.isdir(folder_to_backup):

        backup_to_zip(folder_to_backup)

    else:

        print (f"The folder '{folder_to_backup}' does not exist or is not a directory.")

 

------------------------------------------------------------------------------------------------

Explanation:

Q. What is zipFile( ) ?

zipfile.ZipFile() is a Python class provided by the zipfile module. It allows you to create, read, write, and extract ZIP files. The zipfile module is part of Python's standard library, so you don't need to install additional packages to use it.

With the zipfile class you can open an existing zip file, or you can create a new zip file.

Here, is the syntax of how zip file is created.


zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True)


Parameters

  • file: The name of the ZIP file (str or file-like object). If you're creating a new ZIP file, provide the name here.
  • mode:
    • 'r': Read (default).
    • 'w': Write, creating a new ZIP file (overwrites if it exists).
    • 'x': Write, creating a new ZIP file (raises an error if it exists).
    • 'a': Append to an existing ZIP file or create a new one.
  • compression: The compression type. Possible values:
    • zipfile.ZIP_STORED: No compression (default).
    • zipfile.ZIP_DEFLATED: Compressed (requires zlib).
    • zipfile.ZIP_BZIP2: BZIP2 compression (requires bz2).
    • zipfile.ZIP_LZMA: LZMA compression (requires lzma).
  • allowZip64: Whether to enable ZIP64 extensions for large files (enabled by default).


data structures and algorithms Web Developer

No comments:

Post a Comment