You can download this code by clicking the button below.
This code is now available for download.
This function is used to extract zip or tar files to a specified output path.
Technology Stack : os, zipfile, tarfile
Code Type : File processing
Code Difficulty : Intermediate
def zip_file(file_path, output_path):
import os
import zipfile
import tarfile
if not os.path.isfile(file_path):
raise FileNotFoundError(f"The file {file_path} does not exist.")
if file_path.endswith('.zip'):
with zipfile.ZipFile(file_path, 'r') as zip_ref:
zip_ref.extractall(output_path)
return f"Extracted {file_path} to {output_path}"
elif file_path.endswith('.tar'):
with tarfile.open(file_path, 'r') as tar_ref:
tar_ref.extractall(output_path)
return f"Extracted {file_path} to {output_path}"
else:
raise ValueError("Unsupported file type. Please provide a .zip or .tar file.")