dmf.io.compress#

dmf.io.compress(input_file: str | Path, compression: str | None = None, output_file: str | Path | None = None, password: str | None = None, **kwargs) Path[source]#

Compress a file or directory into a specified format.

This function compresses a file or directory using various compression formats such as gzip, bzip2, xz, zip, 7z, and tar-based formats. The format can either be specified directly or inferred from the output file extension.

Parameters:
  • input_file (Union[str, Path]) – The path to the input file or directory to be compressed.

  • compression (Optional[str], default=None) – The compression format to use. If not provided, it will be inferred from the output file extension or defaults to “zip”.

  • output_file (Optional[Union[str, Path]], default=None) – The path for the output compressed file. If not provided, it will be derived from the input file path by appending the appropriate file extension.

  • password (Optional[str], default=None) – Password for the archive, supported only for ZIP and 7z formats.

  • kwargs (dict) – Additional keyword arguments to pass to the compression function.

Returns:

The path to the compressed output file.

Return type:

Path

Raises:
  • FileExistsError – If the input file does not exist.

  • ValueError – If both compression and output_file are provided, or if the compression format is unsupported.

  • NotImplementedError – If password protection is specified for a format that does not support it.

Notes

Either compression or output_file must be provided, but not both. If neither is provided, the default compression format “zip” is used.

  • If output_file is provided without a specified compression, the format will be inferred from the file extension.

  • If compression is provided without an output_file, the output file path is derived by appending the appropriate file extension to the input_file path.

  • Password protection is only supported for ZIP and 7z formats.

Examples

Compressing a directory into a zip file

compress("my_folder", compression="zip")

Compressing a file into a gzip file

compress("data.txt", output_file="data.txt.gz")

Compressing a directory with a specified output file and inferred format

compress("my_folder", output_file="my_folder.tar.gz")

Compressing a directory into a password-protected file

compress("my_folder", compression="7z", password="mypassword")