Consider, we have following directory structure:
Location:
/Users/me/Desktop/directory_to_zip/
dir1 dir2 somefile.txt
now, If I use rubyzip to zip the contents of directory_to_zip
using the following code:
directory = '/Users/me/Desktop/directory_to_zip/'
zipfile_name = '/Users/me/Desktop/recursive_directory.zip'
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
Dir[File.join(directory, '**', '**')].each do |file|
zipfile.add(file.sub(directory, ''), file)
end
end
This will create a zip file named recursive_directory.zip
, which will contain a container directory called directory_to_zip
& inside directory_to_zip
, will I find my files(dir1 dir2 somefile.txt
)
HOw do I skip creation of directory_to_zip
inside recursive_directory.zip
, so that the zip file just contains the contents of directory_to_zip
& not the directory itself.
Use the zipfile module to create a zip archive of a directory. Walk the directory tree using os. walk and add all the files in it recursively.
Creating a zip folder allows files to be organized and compressed to a smaller file size for distribution or saving space. Zip folder can have subfolders within this main folder.
To add all files in the folder and subfolder, we can use the -r command, which will compress all the files in the folder.
By default, the zip command doesn't archive a directory recursively. By using the flag -r, zip will traverse subdirectories recursively and archive their files. Running the command with option -r ensures the files within the directory are included as well.
Okay, I solved this on my own. If you are in same boat, here is here how I did it:
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
Dir.chdir directory
Dir.glob("**/*").reject {|fn| File.directory?(fn) }.each do |file|
puts "Adding #{file}"
zipfile.add(file.sub(directory + '/', ''), file)
end
end
This works exactly I want. the limitation here here is that it doesn't handle empty directories. Hopefully, it would help someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With