By Jun -
Support me on Amazon
Issue:
I was wondering how I can zip all the files in a folder but without including the directories.
First, I found the two ways listed in
resource 1.
> cd folderName
> zip -r output.zip
OR
> zip -j output.zip folderName/*
What does -j flag do?
Using -j flag, it will flatten all the directories, what you will see in your zipped folder would be all the files within a parent directory.
Zip flags
if you run zip command, you can see a list of flags
> zip
Copyright (c) 1990-2008 Info-ZIP - Type 'zip "-L"' for software license.
Zip 3.0 (July 5th 2008). Usage:
zip [-options] [-b path] [-t mmddyyyy] [-n suffixes] [zipfile list] [-xi list]
The default action is to add or replace zipfile entries from list, which
can include the special name - to compress standard input.
If zipfile and list are omitted, zip compresses stdin to stdout.
-f freshen: only changed files -u update: only changed or new files
-d delete entries in zipfile -m move into zipfile (delete OS files)
-r recurse into directories -j junk (don't record) directory names
-0 store only -l convert LF to CR LF (-ll CR LF to LF)
-1 compress faster -9 compress better
-q quiet operation -v verbose operation/print version info
-c add one-line comments -z add zipfile comment
-@ read names from stdin -o make zipfile as old as latest entry
-x exclude the following names -i include only the following names
-F fix zipfile (-FF try harder) -D do not add directory entries
-A adjust self-extracting exe -J junk zipfile prefix (unzipsfx)
-T test zipfile integrity -X eXclude eXtra file attributes
-y store symbolic links as the link instead of the referenced file
-e encrypt -n don't compress these suffixes
-h2 show more help
How to run it using subprocess? Solution:
From resource 3 below, I learnt that I can use glob to use wildcard in the command like the following:
import glob
import subprocess
subprocess.call(['zip', '-j', 'output.zip'] + glob.glob('example/*'))
What is glob.glob?
(Taken from
python glob doc) It returns a possibly-empty list of path names that match pathname, which must be a string containing a path specification.
In short, it returns a list of path based on Unix shell rules and thus, wildcard would work.
Example of glob from python doc:
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
Resources:
1
How to zip files in mac without root folder
2
Zip the contents of a folder without including the folder itself StackOverflow thread
3
why-does-python-subprocess-zip-fail-but-running-at-shell-works StackOverflow thread
Thanks for reading!
Comments
Post a Comment