File Compression Tool

Setup Your Environment

Make sure you have Python installed on your machine. You can check this by running:

bashCopy codepython --version

If you need to install Python, you can download it from python.org.

Step 2: Create the Compression Tool

Create a file named file_compression_tool.py and add the following code:

pythonCopy codeimport zipfile
import os

def compress_file(input_file, output_zip):
    """Compress a single file into a ZIP file."""
    with zipfile.ZipFile(output_zip, 'w') as zipf:
        zipf.write(input_file, os.path.basename(input_file))
    print(f"Compressed '{input_file}' into '{output_zip}'.")

def decompress_file(input_zip, output_dir):
    """Decompress a ZIP file into a specified directory."""
    with zipfile.ZipFile(input_zip, 'r') as zipf:
        zipf.extractall(output_dir)
    print(f"Decompressed '{input_zip}' into '{output_dir}'.")

def main():
    while True:
        print("\nFile Compression Tool")
        print("1. Compress a file")
        print("2. Decompress a file")
        print("3. Exit")
        
        choice = input("Choose an option (1-3): ")

        if choice == '1':
            input_file = input("Enter the path of the file to compress: ")
            output_zip = input("Enter the name of the output ZIP file: ")
            compress_file(input_file, output_zip)
        elif choice == '2':
            input_zip = input("Enter the path of the ZIP file to decompress: ")
            output_dir = input("Enter the output directory: ")
            decompress_file(input_zip, output_dir)
        elif choice == '3':
            print("Exiting the tool.")
            break
        else:
            print("Invalid choice. Please try again.")

if __name__ == "__main__":
    main()

Step 3: Running the Tool

  1. Open your terminal (or command prompt).
  2. Navigate to the directory where you saved file_compression_tool.py.
  3. Run the script using the command:bashCopy codepython file_compression_tool.py

How It Works

  • Compress a File: When you choose to compress a file, you’ll be prompted to provide the path of the file you want to compress and the name of the output ZIP file. The script will create a ZIP file containing the specified file.
  • Decompress a File: If you choose to decompress a file, you’ll need to specify the path of the ZIP file and the directory where you want to extract the files.

Example Usage

  1. To compress a file named example.txt into example.zip, you would select option 1, input the file path, and then the desired ZIP file name.
  2. To decompress example.zip into a folder called output, choose option 2, input the ZIP file path, and the output directory.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *