Compressing Files With Python, Perl, Ruby and Php
Compressing files
is one of the most common tasks any programmer would have done. The below is a simple comparison of compression paradigms of selected programming languages i have really liked!
This post is much influenced by :
Senario : A list called ‘songs’ with file paths to different songs in the HDD which needs to be compressed to a single zip file.
Ok let the fight begin!
First up is python :
#!/usr/bin/python
import zipfile
""" Open a file called album.zip to write """
with zipfile.ZipFile('album.zip', 'w') as zipit:
""" zipit! """
for song in songs:
zipit.write(song)
Lets compress it in perl :
#!/usr/bin/perl
use strict;
use warnings;
use Archive::Zip;
my $compressor = Archive::Zip->new();
foreach my $song (@songs)
{
$compressor->addFile($song);
}
$compressor->writeToFileNamed('album.zip');
Ok it’s ruby’s turn :****
#!/usr/bin/ruby
require 'rubygems'
require 'zip/zip'
Zip::ZipFile.open('album.zip', Zip::ZipFile::CREATE) {
|zipit|
zipit.get_output_stream(song) {
|f| f.puts open(url.chomp).read
}
}
PHP you may zip it!
<?php
$zip = new ZipArchive();
$zip->open('album.zip', ZIPARCHIVE::CREATE);
foreach($songs as $song)
{
$zip->addFile($song,$song);
}
$zip->close();
?>
Indeed there will be better ways of doing the same! Do share it!
#javascript#linux
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.