Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #217 Create a Zip archive

Create a zip-file with filename name and add the files listed in list to that zip-file.

import zipfile
with zipfile.ZipFile(name, 'w', zipfile.ZIP_DEFLATED) as zip:
    for file in list_:
        zip.write(file)
import "archive/zip"
import "bytes"
import "os"
import "io"
buf := new(bytes.Buffer)
w := zip.NewWriter(buf)
for _, filename := range list {
	input, err := os.Open(filename)
	if err != nil {
		return err
	}
	output, err := w.Create(filename)
	if err != nil {
		return err
	}
	_, err = io.Copy(output, input)
	if err != nil {
		return err
	}
}

err := w.Close()
if err != nil {
	return err
}

err = os.WriteFile(name, buf.Bytes(), 0777)
if err != nil {
	return err
}
uses Zipper, Classes;
Zip := TZipper.Create;
Zip.FileName := name;
Zip.Entries.AddFileEntries(list);
Zip.ZipAllFiles;
Zip.Free;
use v5.10;
use IO::Compress::Zip qw(zip $ZipError);
my @list = ( 'file_A.txt', 'file_B.txt' );

zip \@list => 'name.zip'
    or die "zip failed: $ZipError\n";
use zip::write::FileOptions;
let path = std::path::Path::new(_name);
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file); zip.start_file("readme.txt", FileOptions::default())?;                                                          
zip.write_all(b"Hello, World!\n")?;
zip.finish()?;
use zip::write::FileOptions;
fn zip(_name: &str, _list: Vec<&str>) -> zip::result::ZipResult<()>
{
    let path = std::path::Path::new(_name);
    let file = std::fs::File::create(&path).unwrap();
    let mut zip = zip::ZipWriter::new(file);
    for i in _list.iter() {
        zip.start_file(i as &str, FileOptions::default())?;
    }
    zip.finish()?;
    Ok(())
}

New implementation...
< >
Bart